我想将HaveBox用于依赖注入。但这不是HaveBox的问题。所以我创建了基本控制器:
public abstract class BaseController : Controller
{
protected readonly IRepository m_Repository;
protected BaseController(IRepository repository)
{
m_Repository = repository;
}
}
我的HomeController继承自BaseController
。将HaveBoxConfig.RegisterTypes();
添加到Application_Start
方法并HaveBoxConfig
的实施是:
public class HaveBoxConfig
{
public static void RegisterTypes()
{
var container = new Container();
container.Configure(config => config.For<IService>().Use<Service>());
container.Configure(config => config.For<IRepository>().Use<Repository>());
IDependencyResolver resolver = DependencyResolver.Current;
var newResolver = new MyResolver(container, resolver);
DependencyResolver.SetResolver(newResolver);
}
}
我的解析器:
public class MyResolver : IDependencyResolver
{
private readonly IContainer m_container;
private readonly IDependencyResolver m_resolver;
public MyResolver(IContainer container, IDependencyResolver resolver)
{
m_container = container;
m_resolver = resolver;
}
public object GetService(Type serviceType)
{
try
{
return m_container.GetInstance(serviceType);
}
catch (Exception ex)
{
return m_resolver.GetService(serviceType);
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
return m_resolver.GetServices(serviceType);
}
}
方法GetService
要求使用下一种类型:IControllerFactory
,IControllerActivator
,HomeController
,但不适用于我的IRepository
。
我做错了什么?为什么没有为IRepository
执行DI?
答案 0 :(得分:2)
您还需要实现控制器工厂。最简单的方法是继承DefaultControllerFactory。您可以使用Castle Windsor检查他们是如何做到的。然后你告诉ASP.NET MVC使用你的实现。
DependencyResolver.SetResolver(newResolver);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
答案 1 :(得分:2)
我已经检查了不同的解决方法。最简单的只是将我的控制器添加到容器中。例如:
container.Configure(config => config.For<HomeController>().Use<HomeController>());
简单明了。如果您有复杂的项目和更优雅的解决方案,您可以通过反映实现IController
接口的所有类。