Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a class "DependencyResolver" where I return instances of objects by hand. There I used "Activator.CreateInstance". I wanted to change it so it uses autofac.

My function "Get" works fine:

      public T Get<T>()
        {
            return _container.Resolve<T>();
        }

But I also have a function "CreateNew" where I need a new instance:

      public T CreateNew<T>()
        {
            return _container.Resolve<T>();
        }

The Problem is that I always get the same instance. My Registration looks like this:

            var builder = new ContainerBuilder();
            foreach (var dllFileName in DependencyMapping.GetAllDllFilenames())
            {
                builder
                    .RegisterAssemblyTypes(Assembly.LoadFile(Path.Combine(GetPathFromInstalledSys(), dllFileName)))
                    .AsImplementedInterfaces()
                    .SingleInstance();
            }
            _container = builder.Build();

So there is a place where I can control the behaviour: "SingleInstance" or "InstancePerDependency". But I dont know whether the user needs a new instance or not. Is there any way to change the behavior when "CreateNew" is called?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
681 views
Welcome To Ask or Share your Answers For Others

1 Answer

Lifetime scope (single instance, instance per dependency) is controlled at registration time, not resolve time. There's no way to change it. This is the case with all DI containers, not just Autofac. Part of the point of it is that the consumer shouldn't have to know what scope they want - they just ask for a thing and get it.

Consumers also generally shouldn't deal with disposal - things get disposed by the container.

Note what you have here is service location (client asks the container for a thing), not dependency injection (client takes dependencies in constructor and doesn't know about the container). While service location is sometimes required, generally try to avoid it if you can; it's not really much better than just calling new in your code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...