I have an interface for Data Access Layer (IDal)
public interface IDal<T>{
void Write(T object);
T Read();
}
And I have two classes that has implemented this interface, which access data from two different source.
public class Source1<T>:IDal<T>{
public void Write(T object){ }
public T Read(T object){ }
}
public class Source2<T>:IDal<T>{
public void Write(T object){ }
public T Read(T object){ }
}
And I have a common service interface
public interface IService<T>{
T Get(int id);
T Save(T obj);
T Update(T obj);
T Delete(int id);
}
and I have a service class that has imeplemented service interface
public class Service<T> : IService<T>{
IDal<T> _dal;
public Service(IDal<T> dal){
_dal = dal;
}
public T Get(int id) { }
public T Save(T obj) { }
public T Update(T obj) { }
public T Delete(int id) { }
}
And I have two different controller
public class Bank1Controller(){
IService<Bank1Properties> _service;
public Bank1Controller(IService<Bank1Properties> service){
_service = service
}
}
public class Bank2Controller(){
IService<Bank2Properties> _service;
public Bank2Controller(IService<Bank2Properties> service){
_service = service
}
}
here i want to inject Source1 DAL to Bank1 and Source2 to Bank2 from Unity Dependency Since both source1 and source2 are inherited from IDal.
container.RegisterType<IService<Bank1Properties>, Service<Bank1Properties>>();
container.RegisterType<IDal<Bank1Properties>, Source1<Bank1Properties>>();
container.RegisterType<IDal<Bank2Properties>, Source2<Bank2Properties>>();
Here my both controller try to acces source2, but i want to inject Bank1 = source1 and Bank2 = source2. How do i conditionaly resolve it.
If i register the type this way, it works perfectly, but I don't know this is good way or not. Is there any better way.
container.RegisterType<Bank1Controller>(new InjectionConstructor(
new Service<Bank1Properties>(new Source1<Bank1Properties>())
));
container.RegisterType<Bank2Controller>(new InjectionConstructor(
new Service<Bank2Properties>(new Source1<Bank2Properties>())
));