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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With