简体   繁体   中英

Constructor dependency injection is initializing service

I am using Autofac .

  builder.RegisterType<LogHelper>().As<ILogger>().InstancePerLifetimeScope();

I am registering the service of as an InstancePerLifetimeScope . So only one instance is created in one Lifetime scope.

using (var container = Container.BeginLifetimeScope())
                {
var logger = container.Resolve<ILogger>();
                    var logge1r = container.Resolve<ILogger>();
                    var logger1 = container.Resolve<ILogger>();
 var repobackup = container.Resolve<IRepoBackup>();
                    repobackup.StartProcess();
                }

These two resolves gives me same instance.

 var logger1 = container.Resolve<ILogger>();
 var logger2 = container.Resolve<ILogger>();

Some services required this service by dependency injection.

var repobackup = container.Resolve<IRepoBackup>();

this above line initializes the RepoBackupImplemetaion class which require the ILogger instance but as this resolve is in same LifeTimeScope so same instance should be passed but new instance created every time a constructor with this dependency is called.

 internal class RepoBackupImplemetaion : IRepoBackup
    {
        public RepoBackupImplemetaion(ILogger logger)
        {
            LogHelper = logger;
      }
    }

I registered this service as InstancePerLifetimeScope .

Am i missing something?

It means somewhere in your code a new scope is getting created.

You may use SingleInstance() instead of InstancePerLifetimeScope() if the only issue is related to have only single instance of ILogger interface.

InstancePerLifetimeScope() creates instances for every nested lifetime scope. For this reason when you call your constructor every time it creates different instances. The reason is that, the scope is also different for every call.

You should use single instance to serve your meet. because it returns one instance from all requests in the root and all nested scopes.

builder.RegisterType<LogHelper>().As<ILogger>().SingleInstance();

check this link to get more information:

https://autofaccn.readthedocs.io/en/latest/lifetime/instance-scope.html#instance-per-lifetime-scope

Thanks.

It turns out LogHelper service is also used by a service which is set as SingleInstance(). For that a new instance is created for SingleInstance(). I change the SingleInstance to InstancePerLifetimeScope and now it works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM