c# – 依赖注入不知道我想要注入的类型

前端之家收集整理的这篇文章主要介绍了c# – 依赖注入不知道我想要注入的类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用 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);
原文链接:https://www.f2er.com/csharp/99374.html

猜你在找的C#相关文章