Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject dependency property using Ioc Unity

I have the following classes:

public interface IServiceA
{
    string MethodA1();
}

public interface IServiceB
{
    string MethodB1();
}

public class ServiceA : IServiceA
{
    public IServiceB serviceB;

    public string MethodA1()
    {
        return "MethodA1() " +serviceB.MethodB1();
    }
}

public class ServiceB : IServiceB
{
    public string MethodB1()
    {
        return "MethodB1() ";
    }
}

I use Unity for IoC, my registration looks like this:

container.RegisterType<IServiceA, ServiceA>(); 
container.RegisterType<IServiceB, ServiceB>(); 

When I resolve a ServiceA instance, serviceB will be null. How can I resolve this?

like image 488
Jin Ho Avatar asked Apr 22 '12 11:04

Jin Ho


People also ask

Is IoC a dependency injection?

Spring IoC is achieved through Dependency Injection. Dependency Injection is the method of providing the dependencies and Inversion of Control is the end result of Dependency Injection. IoC is a design principle where the control flow of the program is inverted.

How do you inject dependencies?

The injector class injects dependencies broadly in three ways: through a constructor, through a property, or through a method. Constructor Injection: In the constructor injection, the injector supplies the service (dependency) through the client class constructor.

Is Unity IoC container?

Unity is an IoC container released by Microsoft and is very simple, flexible and easy to use. Though there are many IoC containers available in the market much stronger than Unity, for simplicity and to understand the basic concepts, it's one of the best choices.


1 Answers

You have at least two options here:

You can/should use constructor injection, for that you need a constructor:

public class ServiceA : IServiceA
{
    private IServiceB serviceB;

    public ServiceA(IServiceB serviceB)
    {
        this.serviceB = serviceB;
    }

    public string MethodA1()
    {
        return "MethodA1() " +serviceB.MethodB1();
    }
}

Or Unity supports property injection, for that you need a property and the DependencyAttribute:

public class ServiceA : IServiceA
{
    [Dependency]
    public IServiceB ServiceB { get; set; };

    public string MethodA1()
    {
        return "MethodA1() " +serviceB.MethodB1();
    }
}

The MSDN site What Does Unity Do? is a good starting point for Unity.

like image 56
nemesv Avatar answered Sep 22 '22 12:09

nemesv