Generic Ninject Context Snaps

I have a common interface IRepository<T>and two implementations xrmRepository<T>andefRepository<T>

I want to change the binding based on T, more specifically use xrmRepositorywhen Tcomes from Entity. How can i do this?

I currently have:

kernel.Bind(typeof(IRepository<>)).To(typeof(efRepository<>)).InRequestScope();
kernel.Bind(typeof(IRepository<>)).To(typeof(xrmRepository<>)).When(request => request.Service.GetGenericArguments()[0].GetType().IsSubclassOf(typeof(Entity))).InRequestScope();

But when I try to resolve IRepository<Contact>, it goes into efRepository, although Contact inherits Entity.

I do not want to use Named Bindings, otherwise I will have to add names everywhere.

+5
source share
2 answers

, . , , . - , .

kernel.Bind(typeof(IRepository<>))
      .To(typeof(efRepository<>))
      .InRequestScope();

kernel.Bind<IRepository<Entity>>()
      .To<xrmRepository<Entity>>()
      .InRequestScope();

Edit

xrmRepository , Entity,

kernel.Bind(typeof(IRepository<>))
                    .To(typeof(XrmRepository<>))
                    .When(request => typeof(Entity).IsAssignableFrom(request.Service.GetGenericArguments()[0]));
+2

When .

kernel.Bind(typeof(IRepository<>))
      .To(typeof(efRepository<>))
      .When(request => request.Service.GetGenericArguments()[0] == typeof(Entity))
      .InRequestScope();

kernel.Bind(typeof(IRepository<>))
      .To(typeof(xrmRepository<>))
      .InRequestScope();

kernel.Get<IRepository<Entity>>(); //will return efRepository<Entity>

kernel.Get<IRepository<int>>(); //will return xrmRepository<int>
+1

All Articles