1
votes

I'm using dependency injection with Microsoft Unity. But I'm having problems when I have to Resolve the instances.

My scenario: I have a WPF application and a class library. Unity is installed in the class library.

I'm trying to create an object using the dependency injection.

I got the following error:

The type 'Microsoft.Practices.Unity.IUnityContainer' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.Practices.Unity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=6d32ff45e0ccc69f'.

Code:

UnityDependencyResolver ObjUnityDependencyResolver = new UnityDependencyResolver(UnityContainerConfig.Initialize());
var myclass = ObjUnityDependencyResolver.GetService(typeof(IMyClass));
myclass.HelloWorld(); //Console.Write("Hello World");

This is my unity container:

public static class UnityContainerConfig
{
    private static IUnityContainer _unityContainer = null;

    public static IUnityContainer Initialize()
    {
        if (_unityContainer == null)
        {
            _unityContainer = new Microsoft.Practices.Unity.UnityContainer()
            .RegisterType<IMyClass, MyClass>();
        }

        return _unityContainer;
    }
}

This is my unity resolver:

public class UnityDependencyResolver : IDependencyResolver
{
    private IUnityContainer _unityContainer = null;

    public UnityDependencyResolver(IUnityContainer unityContainer)
    {
        this._unityContainer = unityContainer;
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return _unityContainer.Resolve(serviceType);
        }
        catch
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return _unityContainer.ResolveAll(serviceType);
        }
        catch
        {
            return new List<object>();
        }
    }
}

I have to install the Unity in every single project in my solution?

What's the "better way to create an instance" and use the dependency injection by unity?

1
Is it MVC project ? - Tarek Abo ELkheir
@TarekAboELkheir - I have a WPF application and a class library - smoksnes

1 Answers

1
votes

You only need to install Unity in the client project, and don't use _unityContainer.Resolve(serviceType), if you configure your project carefully, Unity will take care of resolving every service,