I have defined one interface and one class:
public interface IRepository<T>
{
}
public class RoleRepository:IRepository<Domain_RoleInfo>
{
}
Inject here:
public RoleService
{
[Inject]
public RoleService(IRepository<Domain_RoleInfo> rep)
{
_roleRep=rep;
}
}
How can I perform Dependency Injection With Ninject,say how to bind?
I have written a helper class as below, it works fine with non-generic interface.but how to refactor it support generic interface as above?
public class RegisterNinjectModule : NinjectModule
{
public override void Load()
{
BindServices();
BindRepositories();
}
private void BindServices()
{
FindAndBindInterfaces("RealMVC.Service.Interfaces", "RealMVC.Services");
}
private void BindRepositories()
{
FindAndBindInterfaces("RealMVC.Repository.Interfaces", "RealMVC.Repositories");
}
private void FindAndBindInterfaces(string interfaceAssemblyName, string implAssemblyName)
{
//Get all interfaces
List<Type> interfaces = Assembly.Load(interfaceAssemblyName).GetTypes().AsQueryable().Where(x => x.IsInterface).ToList();
IQueryable<Type> ts = Assembly.Load(implAssemblyName).GetTypes().AsQueryable().Where(x => x.IsClass);
foreach (Type intf in interfaces)
{
Type t = ts.Where(x => x.GetInterface(intf.Name) != null).FirstOrDefault();
if (t != null)
{
Bind(intf).To(t).InSingletonScope();
}
}
}
}