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);总结
以上是内存溢出为你收集整理的c# – 依赖注入不知道我想要注入的类型全部内容,希望文章能够帮你解决c# – 依赖注入不知道我想要注入的类型所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)