How to carry out custom initialisation with autofac

泄露秘密 提交于 2019-12-10 17:21:31

问题


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


回答1:


.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.



来源:https://stackoverflow.com/questions/2320536/how-to-carry-out-custom-initialisation-with-autofac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!