Reputation: 437
I would like to register a generic delegate factory for all type or class : is there a way to do it ? Here under a solution that works for registering one type/class at a time.... not very good any other way to do ?
public class Foo<T>
{
public string Name { get; set; }
public T Value;
}
public class FooBuilder<T>
{
public Foo<T> Build(string name)
{
return new Foo<T> { Name = name };
}
}
public delegate Foo<T> FooFactory<T>(string name);
public static void TestFoo()
{
var builder = new ContainerBuilder();
builder.RegisterType<FooBuilder<double>>();
builder.Register<FooFactory<double>>(c => c.Resolve<FooBuilder<double>>().Build);
IContainer container = builder.Build();
var foo1 = container.Resolve<FooFactory<double>>()("foo1");
}
Upvotes: 0
Views: 277
Reputation: 36473
You can register 'open generics' as providing a service. For your example:
var builder = new ContainerBuilder();
// This registers an open generic that can provide all FooBuilder<T>.
builder.RegisterGeneric(typeof(FooBuilder<>));
var container = builder.Build();
// Resolve the builder directly...
var fooBuilder = container.Resolve<FooBuilder<double>>();
// ...or get a factory method if that's what you need
var fooBuilderFactory = container.Resolve<Func<FoodBuilder<double>>>();
Upvotes: 2