我正在尝试在我的MVC应用程序中实现依赖注入。我正在使用Unity.Mvc3.dll
进行IoC。我想知道为什么Unity无法从另一个程序集注册类型。以下是代码:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
var container = new UnityContainer();
// ok: register type from this assembly
container.RegisterType<IMessages, Messages>();
// fail: register type from another assembly (service reference)
container.RegisterType<IPlayerService, PlayerService>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
public class UnityDependencyResolver : IDependencyResolver
{
private readonly IUnityContainer _container;
public UnityDependencyResolver(IUnityContainer container)
{
this._container = container;
}
public object GetService(Type serviceType)
{
try
{
return _container.Resolve(serviceType);
}
catch (Exception ex)
{
throw ex;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return _container.ResolveAll(serviceType);
}
catch (Exception ex)
{
throw ex;
}
}
}
MVC控制器中的使用:
[Dependency]
public IPlayerService PlayerService { get; set; }
[Dependency]
public IMessages Messages { get; set; }
public ActionResult Index()
{
PlayerMessageViewModel vm = new PlayerMessageViewModel();
vm.Messages = Messages; // success!
vm.Players = PlayerService.Get(); // fail: null reference exception :PlayerService
return View(vm);
}
PlayerService
在消息正常的情况下始终为空。
这是 PlayerService
类:
public class PlayerService : IPlayerService
{
private readonly MyDbEntities _dbContext;
public PlayerService()
{
_dbContext = new MyDbEntities();
}
public PlayerService(MyDbEntities dbContext)
{
_dbContext = dbContext;
}
public IQueryable<Player> Get()
{
return _dbContext.Players.AsQueryable();
}
}
这是完整的错误信息
依赖项解析失败,类型 = "System.Web.Mvc.IControllerFactory",名称 = "(none)"。
异常发生在:解析期间。
异常信息:InvalidOperationException - 当前类型 System.Web.Mvc.IControllerFactory 是一个接口,无法构造。您是否缺少类型映射?
public PlayerService()
。 - Pavel Krymets当前类型 System.Web.Mvc.IControllerFactory 是一个接口,不能构造它。你是否缺少类型映射?
- lincx