是否有像Ninject一样的Autofac提供商?

时间:2012-07-18 20:40:57

标签: .net dependency-injection ninject autofac

我有一个问题,是否有针对Ninject的Autofac提供商? 我的意思是,我可以在Autofac中使用它吗?

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

1 个答案:

答案 0 :(得分:5)

我正在查看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框架脱钩。