【发布时间】:2016-05-08 07:07:55
【问题描述】:
我有 ASP.NET MVC5 Web 应用程序,并且我在同一个应用程序中也有 Web API。我正在为 DI 使用 Unity(版本 4)。 我在APP启动时配置Unity容器如下
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
UnityConfiguration.Config();
}
}
public class UnityConfiguration()
{
public void Config()
{
UnityContainer container = new UnityContainer();
container.RegisterType<IMyService, Myservice>();
container.RegisterType<IGenericRepository, GenericRepository>();
container.RegisterType<DbContext, MyEntities>();
}
}
public class GenericRepository:IGenericRepository
{
private DbContext _dbcontext;
public GenericRepository(DbContext dbcontext)
{
_dbcontext = dbcontext;
}
}
public class MyService:IMyService
{
private IGenericRepository _repo;
publi void MyService(IGenericRepository repository)
{
_repo = repository;
}
}
public class MyApiController:ApiController
{
provate IMyService _service;
MyApiController(IMyService myservice)
{
_service = myservice;
}
public IEnumerable<MyModel> GetData()
{
var result = _service.GetData();
return result.ConvertToMyModel();
}
}
但是,当我像
一样调用 urllocalhost://lookup/getdata
我得到错误
类型“LookupController”没有默认构造函数
我该如何解决这个问题?我需要用 Unity 注册我创建的每个控制器还是 Unity 会自动注册所有 MVC 控制器?
【问题讨论】:
-
您必须创建自己的
IControllerFactory和IControllerActivator实现(并在MVC 和Web API 中注册它们)或实现自己的IDependencyResolver(两个框架都有自己的IDependencyResolver抽象) 并注册这些。 -
@steven 谢谢。但是我发现有 Unity.MVC5 和 Unity.Webapi 包 avalble..但是也有用于 ASP.NET MVC 的 Unity 引导程序......所以不确定使用哪一个
标签: asp.net-mvc dependency-injection asp.net-web-api2 unity-container