【问题标题】:Entity Framework DB Context null when using Autofac IOC使用 Autofac IOC 时实体框架 DB 上下文为空
【发布时间】:2017-06-24 16:07:02
【问题描述】:

我正在尝试将查询逻辑移出我的控制器。我的问题是上下文为空,当我尝试获取宠物列表时,在我的具体类 PetRepository 中引发异常。

在界面中:

    public interface IPetRepository
    {
    List<Pet> GetAllPets();   
    PetStoreContext context { get; set; }
    }

在具体实现中:

public class PetRepository : IPetRepository
{
    public PetStoreContext context { get; set; }

    public List<Pet> GetAllPets()
    {
        return context.Pet.ToList(); //this line throws a null exception
    }
 }

在我的控制器中,我正在使用构造函数注入:

public class PetsController : BaseController
{
    private IPetRepository _petRepository;

    public PetsController(IPetRepository petRepository)
    {
        _petRepository = petRepository;
    }
 }

那我的行动结果

public ActionResult Index()
    {            
        var model = new PetListing()
        {
            Pets = _petRepository.GetAllPets()
         }
       return View(model);
     }

最后我只是用 autofac 做一个简单的映射。

  private void RegisterAutoFac()
    {
        var builder = new ContainerBuilder();
        builder.RegisterControllers(Assembly.GetExecutingAssembly());
        builder.RegisterSource(new ViewRegistrationSource());

        builder.RegisterType<PetRepository>().As<IPetRepository>();

        var container = builder.Build();

        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

    }

如果我直接在控制器中使用相同的代码行,那么我会从数据库中获取宠物列表,例如

public ActionResult Index()
{
 public PetStoreContext context = new PetStoreContext();    
return View(context.Pet.ToList());
}

【问题讨论】:

    标签: c# asp.net inversion-of-control autofac


    【解决方案1】:

    context 是一个未设置的属性,而是让 IoC 通过将其注入您的存储库来为您实例化它:

    public class PetRepository : IPetRepository
    {
        private readonly PetStoreContext _context;
    
        public PetRepository(PetStoreContext context)
        {
            _context = context;
        }
    
        public List<Pet> GetAllPets()
        {
            return _context.Pet.ToList();
        }
     }
    

    【讨论】:

    • 谢谢。我是国际奥委会的新手。有没有另一块拼图。现在,当我调用我的控制器时,我遇到了那些令人困惑的 IOC 运行时错误之一:在“PetStore.Repository.PetRepository”类型上使用“Autofac.Core.Activators.Reflection.DefaultConstructorFinder”找到的所有构造函数都不能用可用的服务和参数:无法解析构造函数“Void .ctor(PetStore.PetStore.DAL.Context.PetStoreContext)”的参数“PetStore.PetStore.DAL.Context.PetStoreContext context”。
    • 看起来你需要用Autofacstackoverflow.com/questions/29560294/…注册上下文
    • 您原来的答案是正确的。我没有实例化上下文。我通过创建一个带有更新上下文的具体实现的 BaseRepository 接口来解决这个问题。然后我使用 IOC 将 BaseRepo 传递给 PetRepo 构造函数,Bob 就是你叔叔。再次感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多