cobolstinks
cobolstinks

Reputation: 7153

Unity IoC Explicitly ask container for new instance

It appears that Unity IoC defaults to creating a new instance of an object when it resolves a type. But my question is there someway to be explicit and tell my container that whenever I have it resolve an object type to give me a new instance of said type?

IE i want to be explicit and force the container to make sure theInstance is a new instance each time it resolves type:MyNewObject (or all types for that matter)

MyNewObject theInstance = container.Resolve<MyNewObject>();

Upvotes: 1

Views: 1159

Answers (2)

Alastair Maw
Alastair Maw

Reputation: 5492

If you're applying IoC principles properly, your class declares its dependencies and then the container handles the lifecycles of them. For example, you want to grab an HttpRequest object and the container handles providing the current thread-local one, or whatever.

Your code shouldn't really have to care about the life-cycle of its dependencies, as it should never be responsible for clearing up after them or what-have-you (all of that should be encapsulated in the dependency itself, and invoked by the container when it is shut down).

However, if you do need to care in your code about whether you get a singleton instance or a per-injected instance of the same type, I like to be explicit about it by using the type system itself, just as the Guice container for Java does with its Provider pattern. I've created a Guice-style IProvider<T> interface that I use to do this, and I just wire it up with a simple static factory method for them like so:

Provider.Of<Foo>(() => { /* Code to return a Foo goes here */})

Upvotes: 0

oleksii
oleksii

Reputation: 35925

Yes it is easily configurable by a TransientLifetimeManager

When you register a class should have something like

container.Register<IMyNewObject, MyMewObject>(new TransientLifetimeManager());
//or
container.Register<MyMewObject>(new TransientLifetimeManager())

Upvotes: 2

Related Questions