【问题标题】:Are there Providers for Autofac like providers for Ninject?是否有类似 Ninject 提供程序的 Autofac 提供程序?
【发布时间】:2012-07-18 20:40:56
【问题描述】:

我有一个问题,Autofac 的提供者是否像 Ninject 的提供者一样? 我的意思是,我可以在 Autofac 中使用类似的东西吗?

Bind <ISessionFactory> ().ToProvider(new IntegrationTestSessionFactoryProvider());

【问题讨论】:

    标签: .net dependency-injection ninject autofac


    【解决方案1】:

    我正在查看 Ninject 的 Providers and the Activation Context,似乎 Providers 是一个接口,用于处理 Autofac 只能使用 lambda 处理的场景。在 Ninject 的例子中,他们有:

    Bind<IWeapon>().ToProvider(new SwordProvider());
    
    abstract class SimpleProvider<T> {
    // Simple implementations of the junk that you don't care about...
    
        public object Create(IContext context) {
            return CreateInstance(context);
        }
    
        protected abstract T CreateInstance(IContext context);
    }
    
    class SwordProvider : SimpleProvider<Sword> {
        protected override Sword CreateInstance(IContext context) {
            Sword sword = new Sword();
            // Do some complex initialization here.
            return sword;
        }
    }
    

    与 Autofac 的委托语法相比,所有这些似乎都是疯狂的矫枉过正:

    builder.Register(context =>
                          {
                               Sword sword = new Sword();
                               // Do some complex initialization here.
                               return sword;
                          }).As<IWeapon>();
    

    编辑:如果你的 init 足够复杂以保证它自己的类,你仍然可以这样做:

    builder.RegisterType<SwordFactory>();
    builder.Register(c => c.Resolve<SwordFactory>().Create()).As<IWeapon>();
    
    // this class can be part of your model
    public class SwordFactory
    {
        public Sword Create()
        {
            Sword sword = new Sword();
            // Do some complex initialization here.
            return sword;
        }
    }
    

    这样做的好处是您仍然与您的 DI 框架解耦。

    【讨论】:

    • 好吧,提供者通常不用于如此简单的场景。它们通常用于更复杂的实例化需求,其中委托可能是一个糟糕的选择。我相信你也可以在 Ninject 中对代表做同样的事情。通常,当您想将工厂与 DI 配置分离时,您会使用提供程序,这样工厂可以存在于您的业务层或您想要的任何层中。
    • 你可以从委托中调用工厂类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多