I am currently using/experimenting with autofac as my IoC controller.
Previously to this I used a simple static class defining two methods, similar to
public static TService Resolve<TService>()
public static void Register<IType, ImpType>()
where ImpType must be of IType.
Now over to autofac. When registering, you might do something like
builder.RegisterType<ProductRepository>().As<IProductRepository>();
however if ProductRepository is-not-a IProductRepository you don’t get a compile error?
Is there some way of wiring things up more safely if desired?
Secondly, when building my Ioc modules I use something like
public static class IoCContainer
{
public static IContainer BaseContainer { get; private set; }
public static void Build(ContainerBuilder builder)
{
BaseContainer = builder.Build();
}
}
After I have called IoCContainer.Build(..) I can no longer register anything ‘into’ the BaseContainer. Compare this with the simple model where you can register anything from anywhere. Perhaps this is by design?
I think the
.RegisterType<Foo>.As<IFoo>pattern is not type safe simply because the C# compiler (or the CLR type system) does not handle such type constraints. For example, the following hypothetical declaration of theAsmethod won’t compile:The compiler error is “‘SomeNamespace.IRegistration.As()’ does not define type parameter ‘TImplementation'”.
The following seems to work (though it is discouraged by the best practices section on the Autofac wiki). It will give a compiler error unless
FooimplementsIFoo:cis theIComponentContext. If theFooconstructor requires a constructor argument then you can writec => new Foo(c.Resolve<IBar>()).You can update the container in Autofac 2.2.