eyeballpaul
eyeballpaul

Reputation: 1735

Dependency Injection with Unity and creating objects dynamically in a lower layer

I have just started using Unity (for Dependency Injection) and I have managed to get this working perfectly for MVC and WCF. Everything is extracted out in interfaces, and using constructor injection, all objects are created down the chain for what I set up in my container at application entry point.

My problem now, is that I have a WPF app. I am trying to do something similar and it works for most things, but I have one scenario that I am not 100% sure how to deal with to properly use DI.

Say, my WPF app resolves class A, which takes in interfaces for class B, C etc through constructor injection. Now say, that these objects are around for the lifetime of the app. And now at some point during runtime, class B needs to dynamically create a new version of class D to run in its own thread. How can this be done properly?

The only method I can come up with, is that class A also takes in a new interface E, and all this class does is create class D, and return it as interface D when needed.

But this seems to be more of a factory pattern rather than DI.

To give some context to this, imagine that the application injects the business logic classes and repository classes needed at the resolve at the highest level of the application. Now at some point during runtime it needs to spawn a new repository object on its own thread, to do something very specific. This could be one thread, or multiple depending on what the program is doing.

My suggestion, was to inject a creation class through DI, and this class would have implemented an interface method to GetNewRepositoryObjectOnNewThread() or something similar, which the concrete implementation basically news up a hard coded implementation of the repository.

Any thoughts? I know that's a lot of text to read through!

Upvotes: 1

Views: 1037

Answers (2)

Sebastian Weber
Sebastian Weber

Reputation: 6806

What's the problem with injecting a factory into your classes? DI and the factory pattern play well together.

Upvotes: 1

cynic
cynic

Reputation: 5405

In Unity, you can declare a dependency on Func<TDependency>, and you get a delegate that resolves the dependency any time you call it. So you can register the TDependency with the lifetime manager of your choice (per thread, per call, transient etc.) - the registration can be named, if you don't wish to disturb your default registration - and use it at such "specific points".

Upvotes: 1

Related Questions