Are there Providers for Autofac like providers for Ninject?
.net, autofac, dependency-injection, ninject
Solution
I'm looking at Ninject's Providers and the Activation Context and it appears that Providers are an interface to handle scenarios that Autofac would just handle with a lambda. In Ninject's example, they have:
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;
}
}
All this seems like crazy overkill compared to Autofac's delegate syntax:
builder.Register(context =>
{
Sword sword = new Sword();
// Do some complex initialization here.
return sword;
}).As<IWeapon>();
EDIT: If your init is complex enough to warrant its own class, you could still do this:
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;
}
}
Nice thing about this is you're still decoupled from your DI framework.
Problem
I have a question, Are there Providers for Autofac like providers for Ninject? I mean, can I use it something like that in Autofac? ``` Bind <ISessionFactory> ().ToProvider(new IntegrationTestSessionFactoryProvider()); ```