How to perform custom initialization using autofac

I am adding autofac to an existing project, and some of the service implementations require their Initialize method to be called and pass configuration information. I am currently 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 am still creating the object myself, and this is what I am trying to get away from this and let autofac handle it for me. Is it possible to configure the operation of creating a message that will perform user initialization?

To give you an idea that I'm ideally, this will be the code:

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

Update: I am using Autofac-2.1.10.754-NET35

+3
source share
1 answer
.OnActivating(e => e.Instance.Initialize(...))

gotta do the trick.

Startable (. Autofac).

, , .

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

.

+5

Source: https://habr.com/ru/post/1734111/


All Articles