Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving AutoFac dependencies inside Module class

I'm new to AutoFac and am currently using custom modules inside my app config to boot up some core F# systems. The code I'm using is

var builder = new ContainerBuilder();
builder.RegisterType<DefaultLogger>().As<IDefaultLogger>();
builder.RegisterModule(new ConfigurationSettingsReader("autofac"));
builder.Build();

And inside my app config I have the appropriate logic to start up the relevant systems. I would like to have access to the DefaultLogger inside my Modules. Metadata for the Module base class has the following options available to me:

protected virtual void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration);

protected virtual void AttachToRegistrationSource(IComponentRegistry componentRegistry, IRegistrationSource registrationSource);

public void Configure(IComponentRegistry componentRegistry);

protected virtual void Load(ContainerBuilder builder);

I've only been using Load so far and I can't see any methods on the builder that would allow me to get at the logging service.

like image 901
Jesse Carter Avatar asked May 01 '14 14:05

Jesse Carter


People also ask

What is Autofac dependency injection?

Autofac is an open-source dependency injection (DI) or inversion of control (IoC) container developed on Google Code. Autofac differs from many related technologies in that it sticks as close to bare-metal C# programming as possible.

Why should I use Autofac?

AutoFac provides better integration for the ASP.NET MVC framework and is developed using Google code. AutoFac manages the dependencies of classes so that the application may be easy to change when it is scaled up in size and complexity.

What is resolve in Autofac?

After you have your components registered with appropriate services exposed, you can resolve services from the built container and child lifetime scopes. You do this using the Resolve() method: var builder = new ContainerBuilder(); builder. RegisterType<MyComponent>(). As<IService>(); var container = builder.

What is module in Autofac?

The module exposes a deliberate, restricted set of configuration parameters that can vary independently of the components used to implement the module. The components within a module still make use dependencies at the component/service level to access components from other modules.


1 Answers

When registering something within your modules with autofac instead of using RegisterType method you might use Register method:

builder.Register(c =>
   {
       IComponentContext ctx = c.Resolve<IComponentContext();
       IDefaultLogger logger = ctx.Resolve<IDefaultLogger>();
       ...do something with logger...
       return ...return object you want to register...;
    });
like image 122
mr100 Avatar answered Oct 29 '22 22:10

mr100