English 中文(简体)
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

最佳回答
.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.

问题回答

暂无回答




相关问题
Validate interface using IoC

I have a domain model that uses IoC with Microsoft Unity. For the validation I use VAB and I decorate the interface, not the entity. The code the following: interface IJob : IValidable { [...

Injecting Subsonic SimpleRepository class to controller

I m tryingot get started with IoC, I have an MVC project in which is use subsonic, I m trying to inject subsonic simplerepository to my controllers but I m getting this error: StructureMap Exception ...

Unity view Registered Types during debug

Possibly a stupid question, but during debug I simply want to see the types that have been registered with my Unity container. I have tried going through the container in the watch window, but can t ...

ASP.NET MVP Injecting Service Dependency

I have an ASP.NET page that implements my view and creates the presenter in the page constuctor. Phil Haack s post providing was used as the starting point, and I ll just the examples from the post ...

Unity Container Disposing and XML Web Service

I am registering some wrapers over un-managed objects in container. How can I dispose of them at the end of the container s lifetime? Please bear in mind I have an XML Web service.

热门标签