【发布时间】: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