我想使用
HaveBox进行依赖注入.但这不是关于
HaveBox的问题.所以我创建了基本控制器:
public abstract class BaseController : Controller { protected readonly IRepository m_Repository; protected BaseController(IRepository repository) { m_Repository = repository; } }
我的HomeController继承自BaseController.添加HaveBoxConfig.RegisterTypes();到HaveBoxConfig的Application_Start方法和实现是:
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?
解决方法
您还需要实现一个控制器工厂.最简单的方法是子类化
DefaultControllerFactory.你可以用
Castle Windsor检查它们是如何做到的.然后你告诉ASP.NET MVC使用你的实现.
DependencyResolver.SetResolver(newResolver); ControllerBuilder.Current.SetControllerFactory(controllerFactory);