【问题标题】:Does Unity offer anything similar to Ninject custom providers?Unity 是否提供类似于 Ninject 自定义提供程序的功能?
【发布时间】:2011-03-03 09:39:33
【问题描述】:

Unity(任何版本)是否提供类似于here 所述的 Ninject 自定义提供程序?我需要在类型解析时访问上下文信息。具体来说,我需要访问调用解析的类型。

【问题讨论】:

    标签: dependency-injection unity-container ioc-container ninject


    【解决方案1】:

    我不确定您是否可以直接执行此操作,但我认为您可以通过执行以下操作来实现类似的效果:

        public interface IMyType
    {
        //whatever you need
    }
    
    public interface IMyTypeProvider
    {
        IMyType Create(object context);
    }
    
    public class MyTypeProvider : IMyTypeProvider
    {
        public IMyType Create(object context)
        {
            //construct required instance based on context
        }
    }
    
    public class ClassWhichNeedsMyType
    {
        public ClassWhichNeedsMyType(IMyTypeProvider provider)
        {
            this.myType = provider.Create(this);
        }
    
        private IMyType myType;
    }
    

    然后将提供程序注册到容器中,并使用它来构建您的依赖项:

    container.RegisterType<IMyTypeProvider, MyTypeProvider>();
    

    【讨论】:

    • 谢谢,最终使用了类似的方法
    猜你喜欢
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多