Search code examples
c#uwpunity-container

Can I do a RegisterType in one project and Resolve this interface in another project using Unity Containers?


I have a VS solution A which contains an interface foo

public interface IFoo
{
 //some methods
}

I have a solution B which implements this Interface

public class Bar : IFoo
{ 
  //methods implemented here
}

App.xaml.cs in Solution B uses unity container to register this

App.xaml.cs

//code

this.unityContainer.RegisterType<IFoo, Bar>();

Now in solution A, can I resolve IFoo?

SOLn A

Class A
{
   this.unityContainer.resolve<IFoo>(); //get error here
}

Since the type IFoo, Bar is not registered in the same solution, I get the error a type cannot be resolved. Is there a workaround which makes this possible?


Solution

  • There's no difference in what project you do a registrations as far as you "share" one unity container between projects.

    It's a standard way of registering dependencies - but remember! you have to share the ioc container instance some way.

    Example

    #Project A (no dependencies)

    interface IFoo {}
    

    #Project B (depends on A)

    unityContainer.RegisterType<IFoo, Bar>();
    

    #Project C (depends on A)

    unityContainer.resolve<IFoo>();
    

    But agin, you have to share the UnityContainer instance some way. Usually there is Main project that acts like a "glue" between those projects.

    I can recommend a great book about dependecy inection: https://www.manning.com/books/dependency-injection-principles-practices-patterns

    because you have to understood basic principles and mechanisms.