I have mostly used Ninject, so I apologize if I mix up terminology.
I created a logger module to handle NLog using the destination class name as the logger name. It is very similar to this: http://docs.autofac.org/en/latest/examples/log4net.html?highlight=log4net
I also have a module created in my service layer that takes care of all of the service level registrations. Looks like this:
public class ServiceModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.Register(x => new AccountService(x.Resolve<ILogger>()))
.As<IAccountService>()
.InstancePerRequest();
}
}
Here is my autofac registration:
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterModule(new LoggingModule());
builder.RegisterModule(new ServiceModule());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
app.UseAutofacMiddleware(container);
app.UseAutofacMvc();
At runtime, I get an exception saying ILogger has not been registered, am I missing something about how the modules work that is causing ILogger to not be visible in my service module?
A module can do many things : it can register new components and/or subscribe to Autofac events.
In this case, the
LoggingModuledoesn't registerILog. It intercepts the preparation of other components using thePreparingevent and add a newParameterthat will create theILogif needed.You won't be able to resolve
ILogbut if yourAccountServiceimplementation requires aILogthe followingParameterwill be triggered and will provide theILogimplementation.All you have to do is to register your type without trying to explicitly create the instance :