Introducing the current user with Ninject in this way - any flaws?

I use this ninject binding:

kernel.Bind<ICurrentUser>().To<CurrentUser>() .InRequestScope() .WithConstructorArgument("principal", context => (RolePrincipal HttpContext.Current.User); 

In one of my service level decorators, I simply add "ICurrentUser currentUser" to the constructor to get the object and its operation.

Are there any flaws in this implementation, or is there a better way to implement its surrounding context? A custom object is created for each request - also if its an anonymous user.

+6
source share
1 answer

Ambient use for context is very limited, and using constructor injection usually gives the best results.

Consider, for example, how using Ambient context makes unit testing more difficult. Using the Ambient context usually means that you need to change this context in the test setup and delete it in test mode. But the unit test structure usually runs a test suite for multiple threads (e.g. MSTest), and when you use a static variable like this, it means that your tests influence each other.

All this can be easily overcome by entering all the dependencies in the constructor. Or look at it from a different perspective. If your class depends on this service, why not insert into the constructor?

The only thing that bothers me is the explicit registration of the constructor arguments. This makes your configuration more fragile. Since your CurrentUser is RolePrincipal , this allows you to register it directly:

 kernel.Bind<ICurrentUser>().To<CurrentUser>().InRequestScope(); kernel.Bind<RolePrincipal>() .ToMethod(c => (RolePrincipal)HttpContext.Current.User); 
+5
source

All Articles