Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do resolving using Unity in a mutli-project solution

In a new WPF project (VS2010) i 'm using Unity 2 for the first time. In this project i use the following structure:

Solution

WPF Project

Class Library1

Class Library2

Class Library 3 ....

Registering the different types using Unity is done in WPF Project using the following snippet:

IUnityContainer container = new UnityContainer()
                            .RegisterType<IObjectContext, ObjectContextAdapter>()
                            .RegisterType<IConnectionStringProvider, ConnectionStringProvider>()
                            .RegisterType(typeof(IRepository<>), typeof(Repository<>));

Let's say now that i would like to get the Repository<Orders> constructor-injected resolved in Class Library1. Apparently the container is not known in the other projects!

How would i do that?

like image 588
Savvas Sopiadis Avatar asked Jun 10 '10 07:06

Savvas Sopiadis


1 Answers

I mostly agree with Chris' answer, but I think config files are icky (especially for Unity) so here's a solution that will allow you to use runtime config w/o circular references. We're going to do this with registries.

Create an Infrastructure project that will contain IConfigureUnity.

public interface IConfigureUnity
{
    public void Configure(UnityContainer container);
}

Each of your class library projects will be responsible for implementing this interface to register it's own classes.

public class RegistryForSomeClassLibrary : IConfigureUnity
{
    public void Configure(UnityContainer container)
    {
        container
            .RegisterType<IObjectContext, ObjectContextAdapter>()
            .RegisterType<IConnectionStringProvider, ConnectionStringProvider>()
            .RegisterType(typeof(IRepository<>), typeof(Repository<>));
    }
}

Then in your WPF project you'll need to create the container and apply these registries.

var container = new UnityContainer();
new RegistryForSomeClassLibrary().Configure(container);
new RegistryForAnotherClassLibrary().Configure(container);

Now you have a fully configured container instance w/o any config files.

like image 135
Ryan Avatar answered Oct 11 '22 12:10

Ryan