Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting Current User with Ninject this way - any disadvantages?

I'm using this ninject bind:

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

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

Are there any disadvantages by this implementation or is there a better way to implement his ambient context? For each request the user object is created - also if its an anonymous user.

like image 411
Vindberg Avatar asked Oct 22 '12 09:10

Vindberg


People also ask

What are the disadvantages of dependency injection?

The main drawback of dependency injection is that using many instances together can become a very difficult if there are too many instances and many dependencies that need to be resolved.

What is NInject dependency injection?

NInject is a popular IOC container that can be used to inject dependencies in your WebAPI controllers easily. IDG. Dependency injection is a software design pattern that helps you to build pluggable implementations in your application using loosely coupled, testable components.

What are the three types of dependency injection?

There are three main styles of dependency injection, according to Fowler: Constructor Injection (also known as Type 3), Setter Injection (also known as Type 2), and Interface Injection (also known as Type 1).


1 Answers

The use for an Ambient Context is very limited and using constructor injection will usually yield the best results.

Think for instance how the use of an Ambient Context complicates unit testing. Using an Ambient Context would typically mean that you need to change that context in the test setup and remove it in the test teardown. But a unit test framework typically runs a set of tests on multiple threads (as MSTest does for instance) and when you use a static variable like this, it means that your tests influence each other.

[Update] Because this and other reasons, the book Dependency Injection in .NET, Second Edition calls Ambient Context an anti-pattern.

This all can simply be overcome by injecting all dependencies in the constructor. Or let's view it from a different standpoint. If your class depends on this service, why not inject into the constructor?

The only thing that's worrying me is the explicit constructor argument registration. This makes your configuration more brittle. Since your CurrentUser depends on a RolePrincipal, this justifies registering it directly:

kernel.Bind<ICurrentUser>().To<CurrentUser>().InRequestScope();

kernel.Bind<RolePrincipal>()
    .ToMethod(c => (RolePrincipal)HttpContext.Current.User);
like image 77
Steven Avatar answered Sep 28 '22 06:09

Steven