Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to carry out custom initialisation with autofac

I'm adding autofac to an existing project and some of the service implementations require their Initialize method to be called and passed configuration information. Currently I'm using the code:

builder.Register(context =>
                 {
                    var service = 
                         new SqlTaxRateProvider(context.Resolve<IUserProvider>());
                    service.Initialize(config);
                    return service;
                 }
).As<ITaxService>()
.SingleInstance();

which works but I'm still creating the object myself which is what I'm trying to get away from this and allow autofac to handle it for me. Is it possible to configure a post create operation that would carry out the custom initialisation?

To give you an idea of what I'm after ideally this would be the code:

builder.RegisterType<SqlTaxRateProvider>()
 .As<ITaxService>()
 .OnCreated(service=> service.Initialize(config))
 .SingleInstance();

Update: I am using Autofac-2.1.10.754-NET35

like image 750
Damien McGivern Avatar asked Feb 23 '10 18:02

Damien McGivern


People also ask

How do I register an Autofac service?

Register by Type var builder = new ContainerBuilder(); builder. RegisterType<ConsoleLogger>(); builder. RegisterType(typeof(ConfigReader)); When using reflection-based components, Autofac automatically uses the constructor for your class with the most parameters that are able to be obtained from the container.

What is the use of Autofac in MVC?

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.

How do I get Autofac containers?

From Visual Studio, you can get it via NuGet. The package name is Autofac. Alternatively, the NuGet package can be downloaded from the GitHub repository (https://github.com/autofac/Autofac/releases).

What is autofac?

Autofac is an addictive IoC container for . NET. It manages the dependencies between classes so that applications stay easy to change as they grow in size and complexity. This is achieved by treating regular . NET classes as components.


1 Answers

.OnActivating(e => e.Instance.Initialize(...))

should do the trick.

You might also investigate the Startable module (see the Startable entry in the Autofac wiki).

Mark's suggestion to do initialisation in the constructor is also a good one. In that case use

.WithParameter(new NamedParameter("config", config))

to merge the config parameter in with the other constructor dependencies.

like image 138
Nicholas Blumhardt Avatar answered Nov 15 '22 10:11

Nicholas Blumhardt