我有一种奇怪的情况。我需要将Entity Framework 6.2用于我的.net核心应用程序。
普通控制器
public class SampleApiController : BaseController
{
// use _repo and other stuff
}
基本控制器
public class BaseController : Controller
{
protected IRepo_repository;
public BaseController(IRepo repository)
{
_repository = repository;
}
public BaseController() : this(null)
{
}
}
App DBContext
public class SampleContext : DbContext
{
public SampleContext(string connectionString)
:base(connectionString)
{
try
{
this.Database.Log = (s) => System.Diagnostics.Debug.Write(s);
}
catch (Exception e)
{
//CurrentLogger.Log.Error(e);
}
}
public DbSet<Test1> Test1s { get; set; }
public DbSet<Test2> Test2s { get; set; }
}
存储库界面
public interface IRepo
{
// methods definition
}
存储库类
public interface Repo : IRepo
{
// methods implementation
}
Startup.cs - &gt; ConfigureServices方法
services.AddScoped<SampleContext>((s) => new SampleContext(configuration["ConnectionStrings:SampleApp"]));
services.AddScoped<IRepo, Repo>();
在这张图片中,您可以看到存储库参数为空...未使用Repo实例初始化...(!!!在此图片中IRepo是IRepositoryBase)
解决方案!
CodeNotFound和Riscie在评论中说,问题是BaseController初始化为null ...谢谢大家!
答案 0 :(得分:0)
试试这个:
存储库界面
public interface IRepo
{
// methods definition
}
存储库类 我已将其从接口更改为类,并使其实现了IRepo接口
public class Repo : IRepo
{
// methods implementation
}
修改 同时删除第二个构造函数
public class BaseController : Controller
{
protected IRepo_repository;
public BaseController(IRepo repository)
{
_repository = repository;
}
//second constructor most likely introduces the problem
}
答案 1 :(得分:0)
您通常会将IRepo
从SampleApiController
传递到BaseController
。
根据我的理解,BaseController
中不需要任何参数构造函数。如果是,您可能希望将其删除以防止_repository
成为null
。
public class SampleApiController : BaseController
{
public SampleApiController(IRepo repository)
: base(repository)
{
}
}
public class BaseController : Controller
{
protected IRepo _repository;
public BaseController(IRepo repository)
{
_repository = repository;
}
/*public BaseController() : this(null)
{
}*/
}
public interface IRepo
{
// methods definition
}