unitycontainer / configuration

Unity.Configuration package
Apache License 2.0
13 stars 13 forks source link

Configuring Liftetime in registration causes object to immediately Dispose #6

Closed dekenless closed 5 years ago

dekenless commented 6 years ago

I am migrating from 4.0.1 (this all worked in that version) and have something like this (LogInfo implements Dispose):

 <register type="ILogInfo" mapTo="Foo.LogInfo, Foo.Logging">
      <lifetime type="singleton" />
    </register>
var foo = MainContainer.Resolve<ILogInfo>(); 
MainContainer.RegisterInstance<ILogInfo>(foo);

When I register the instance, Dispose is immediately called on foo.

Now, if I change the registration to:

 <register type="ILogInfo" mapTo="Foo.LogInfo, Foo.Logging">
        </register>

And do this, it works:

var foo = MainContainer.Resolve<ILogInfo>(); 
MainContainer.RegisterInstance<ILogInfo>(foo, new .SingletonLifetimeManager());
ENikS commented 6 years ago

What is your question?

dekenless commented 6 years ago

No question, pointing out there is a problem when configuring via a config file. Calling RegisterInstance should not cause Dispose to be called on the class that is being registered.

dekenless commented 6 years ago

Here is a sample solution demonstrating the issue. sample.zip

ENikS commented 6 years ago

Thank you. Perhaps you could fix it as well? I would be happy to merge a PR. I am a bit indisposed at the moment and it might take a while before I could get to this...

dekenless commented 6 years ago

I checked and it was working prior to release 5.7

ENikS commented 5 years ago

When you load your configuration:

 <register type="ILogInfo" mapTo="Foo.LogInfo, Foo.Logging">
      <lifetime type="singleton" />
    </register>

Unity creates singleton registration for type ILogInfo. When you execute following two lines

var foo = MainContainer.Resolve<ILogInfo>(); 
MainContainer.RegisterInstance<ILogInfo>(foo);

unity resolves instance in first line and creates new instance registration for the same type ILogInfo in the second.

While doing it, Unity checks if old instance is IDisposable and if yes, disposes it. So, to make long story short, remove this line and everything should work: MainContainer.RegisterInstance<ILogInfo>(foo);