Dynamically Bind UserStore with Ninject

153 Views Asked by At

I have the following user Store:

public class UserStoreService<T> : UserStore<T> where T : IdentityUser
{
    public UserStoreService(MainDbContext context)
        : base(context)
    {
    }
}

In my Startup, I need to bind this with a custom user from another library. I am trying to avoid to have to reference that library in my project altogether. I have the interfaces referenced and that is what I am using throughout the whole project to access properties and such. What I can't figure out is how to dynamically bind the following statement:

kernel.Bind<IUserStore<MyCustomUser>>().To<UserStoreService<MyCustomUser>>();

MyCustomUser extends IdentityUser

2

There are 2 best solutions below

3
BatteryBackupUnit On

So there's two ways to achieve bindings without referencing the implementation-assembly directly:

  • Create bindings in the implementation assembly -- ninject features "Modules" for this, see here. Modules can be loaded, for example, by kernel.Load(AppDomain.CurrentDomain.GetAssemblies())
  • Use reflection to find implementation of interfaces and create bindings -- ninject has Ninject.Extensions.Conventions which can simplify things. You'd probably would want to make use of a custom IBindingGenerator in your case. -- of course you could also roll your own implementation

A word of warning though, many would say that you should employ a composition root and hence you should actually reference the implementation assembly from and create the bindings in the composition root. See Mark Seemann's argumentation.

1
Chris Pratt On

I'm not sure you quite understand what interfaces are for. They give you the ability to swap in implementations, but that doesn't mean that you can completely hide the implementation from the application. Everywhere else in your application, you can reference the interfaces, which is good, but in your Ninject config, you have to tell it what it should bind to that interface when it comes across it, which means you application must have a reference to the project where the implementations exist, if only just for this.