Search code examples
c#genericsdependency-injectionautofac

Register a generic type inside an assembly that implements an interface with autofac


Inside the project Providers I have defined this class

public class MyLogProvider<T> : IMyProvider<T>
    where T : ILoggable 

ILoggable is a simple interface with no methods to implement.

Then, I have a web project with some MVC Controllers that implement the interface ILoggable. For example

public class MyController : Controller, ILoggable
{
    ...
} 

Finally I have a project IoC that is referenced by the web project and that references the project Providers. So inside IoC I cannot use MyController class.

I need to do this kind of registration:

builder.RegisterType<MyLogProvider<MyController>>()
    .As<IMyProvider<MyController>>()
    .InstancePerRequest();

but obviusly I cannot do in that way...

I have also tried with

builder.RegisterGeneric(typeof(Log4NetProvider<>)).As(typeof(Log4NetProvider<>));

and I have looked for to use

builder.RegisterAssemblyTypes(assemblies)

but with no success.


Solution

  • You register the class alone and not the interface.

    builder.RegisterGeneric(typeof(MyProvider<>)).As(typeof(IMyProvider<>));
    

    I assume the interface is what is injected into the controller

    public class MyController : Controller, ILoggable {
        public MyController (IMyProvider<MyController> provider) {
            //...
        }
    }