AutoFac lets you register generic classes with builder.RegisterGeneric(Type type)
, however it does not accept parameters for construction. The description of the method even says:
Register an un-parametrized geenric type
However, what if I have a generic interface IService implemented by Service, which requires some parameters?
Currently I have it registered like this:
builder.Register(c =>
new Service<Class1>(
parameter1,
parameter2))
.As<IService<Class1>>();
In registration I have to specify the exact type of T (Class1 in this case). Can I do it more generically, so that I have one registration working for any T?
Every thing is documented here: https://autofaccn.readthedocs.io/en/latest/register/parameters.html
Basically, you can keep using RegisterGeneric
and use the WithParameter
builder.RegisterGeneric(typeof(Service<>))
.WithParameter("nameOfParam1", parameter1)
.WithParameter("nameOfParam2", parameter2)
.As(typeof(IService<>));