What is the best way to inject repositories into an ASP.NET controller - asp.net-mvc

We have a project written in ASP.NET MVC and we use NInject to inject the repositories into the controllers. Currently we are using properties and the Inject-attribute to inject the repositories, which works well enough:
[Inject]
public IMyRepository MyRepos {get;set;}
An alternative way of injecting would be to do it "manually" using the NInjectServiceLocator:
var myRepos = NInjectServiceLocatorInstance.Resolve<IMyRepository>();
Now I was wondering about the following: the first method requires all repositories to be listed at the top (not necessarily at the top of course, but it's the most logical place) of a controller. Whenever a request is made, NInject instantiates each and every repository. This happens regardless of whether all of the repositories are actually needed inside a specific Action.
With the second method you can more precisely control which repositories are actually necessary and thus this might save some overhead when the controller is created. But you probably also have to include code to retrieve the same repository in multiple places.
So which one would be better? Is it better to just have a bunch of repository-properties or is it better to resolve the repositories which are actually necessary for a specific action when and where you need them? Is there a performance penalty involved for injecting "useless" repositories? Are there (even ;-) better solutions out there?

I prefer constructor injection:
private readonly IMyRepository _repository;
public MyController(IMyRepository repository)
{
_repository = repository;
}
All your dependencies are listed in one operation
Your controller does not need to know anything about NInject
You can unit-test your controller without NInjects involvment by stubbing interfaces straight to the constructor
Controller has a cleaner code
NInject or any other DI framework will do the work behind the scenes and leave you concentrating on the actual problem, not DI.

Constructor Injection should be your default choice when using DI.
You should ask yourself if the controller is really dependent on that specific class to work at all.
Maybe Method injection could also be a solution for specific scenario's, if you have only specific methods that needs dependencies.
I've never used Property Injection but Mark Seeman describes it in his book (Dependency Injection in .NET):
PROPERTY INJECTION should only be used when the class you’re developing has a good
LOCAL DEFAULT and you still want to enable callers to provide different implementations
of the class’s DEPENDENCY.
PROPERTY INJECTION is best used when the DEPENDENCY is optional.
NOTE There’s some controversy around the issue of whether PROPERTY INJECTION
indicates an optional DEPENDENCY. As a general API design principle, I
consider properties to be optional because you can easily forget to assign
them and the compiler doesn’t complain. If you accept this principle in the
general case, you must also accept it in the special case of DI. 4
A local default is described as:
A default implementation of an ABSTRACTION that’s defined in the same assembly as
the consumer.
Unless you're building an API I would suggest not to use Property Injection
Whenever a request is made, NInject instantiates each and every repository. This happens regardless of whether all of the repositories are actually needed inside a specific Action.
I don't think you should worry to much about the performance when using constructor injection

By far my favorite method is:
public class MyController : Controller
{
public IMyRepository MyRepos {get;set;}
public MyController(IMyRepository repo)
{
MyRepos = repo;
}
}
So you can use a NuGet package, such as Ninject.MVC3 (or MVC4) which has specific support for including the Ninject kernel inside the MVC's own IoC classes
https://github.com/ninject/ninject.web.mvc/wiki/MVC3
Once you have Ninject hooks in, you can let it do the work of injection instances into the controller's constructor, which I think is a lot cleaner.
EDIT:
Ahh, OK. Having read your question a bit more thoroughly, I see where you're going with this. In short, if you want to pick and choose which repo classes are instansiated then you will need to manually call, for example:
var myRepos = NInjectServiceLocatorInstance.Resolve<IMyRepository>();
You cannot configure Ninject (or any other IoC AFAIK) to selectively create object instances based on the currently execute method. That level of granularity is a real edge case I feel, which may be solvable by writing your own controller factory class, but that would be overkill.

Related

Laravel 4: Facade vs DI (when to use)

My understanding is that a facade is used as an alternative to dependency injection. Please correct if I'm mistaken. What is not clear is when one should use one or the other.
What are the advantages/disadvantages of each approach? How should I determine when to use one or the other?
Lastly, why not use both? I can create a facade that references an interface. It seems Sentry 2 is written this way. Is there a best practice?
FACADES
Facades are not an alternative to dependency injection.
Laravel Facade is an implementation of the Service Locator Pattern, creating a clean and beautiful way of accessing objects:
MyClass::doSomething();
This is the PHP syntax for a static methods, but Laravel changes the game and make them non-static behind the scenes, giving you a beautiful, enjoyable and testable way of writing your applications.
DEPENDENCY INJECTION
Dependency Injection is, basically, a way of passing parameters to your constructors and methods while automatically instatiating them.
class MyClass {
private $property;
public function __construct(MyOtherClass $property)
{
/// Here you can use the magic of Dependency Injection
$this->property = $property
/// $property already is an object of MyOtherClass
}
}
A better construction of it would be using Interfaces on your Dependency Injected constructors:
class MyClass {
private $property;
public function __construct(MyInterface $property)
{
/// Here you can use the magic of Dependency Injection
$this->property = $property
/// $property will receive an object of a concrete class that implements MyInterface
/// This class should be defined in Laravel elsewhere, but this is a way of also make
/// your application easy to maintain, because you can swap implementations of your interfaces
/// easily
}
}
But note that in Laravel you can inject classes and interfaces the same way. To inject interfaces you just have to tell it wich one will be this way:
App::bind('MyInterface', 'MyOtherClass');
This will tell Laravel that every time one of your methods needs an instance of MyInterface it should give it one of MyOtherClass.
What happens here is that this constuctor has a "dependency": MyOtherClass, which will be automatically injected by Laravel using the IoC container. So, when you create an instance of MyClass, Laravel automatically will create an instance of MyOtherClass and put it in the variable $class.
Dependency Injection is just an odd jargon developers created to do something as simple as "automatic generation of parameters".
WHEN TO USE ONE OR THE OTHER?
As you can see, they are completely different things, so you won't ever need to decide between them, but you will have to decide where go to with one or the other in different parts of your application.
Use Facades to ease the way you write your code. For example: it's a good practice to create packages for your application modules, so, to create Facades for those packages is also a way to make them seem like a Laravel public class and accessing them using the static syntax.
Use Dependency Injection every time your class needs to use data or processing from another class. It will make your code testable, because you will be able to "inject" a mock of those dependencies into your class and you will be also exercising the single responsibility principle (take a look at the SOLID principles).
Facades, as noted, are intended to simplify a potentially complicated interface.
Facades are still testable
Laravel's implementation goes a step further and allows you to define the base-class that the Facade "points" to.
This gives a developer the ability to "mock" a Facade - by switching the base-class out with a mock object.
In that sense, you can use them and still have testable code. This is where some confusion lies within the PHP community.
DI is often cited as making your code testable - they make mocking class dependencies easy. (Sidenote: Interfaces and DI have other important reasons for existing!)
Facades, on the other hand, are often cited as making testing harder because you can't "simply inject a mock object" into whatever code you're testing. However, as noted, you can in fact "mock" them.
Facade vs DI
This is where people get confused regarding whether Facades are an alternative to DI or not.
In a sense, they both add a dependency to your class - You can either use DI to add a dependency or you can use a Facade directly - FacadeName::method($param);. (Hopefully you are not instantiating any class directly within another :D ).
This does not make Facades an alternative to DI, but instead, within Laravel, does create a situation where you may decide to add class dependencies one of 2 ways - either using DI or by using a Facade. (You can, of course, use other ways. These "2 ways" are just the most-often used "testable way").
Laravel's Facades are an implementation of the Service Locator pattern, not the Facade pattern.
In my opinion you should avoid service locator within your domain, opting to only use it in your service and web transport layers.
http://martinfowler.com/articles/injection.html#UsingAServiceLocator
I think that in terms of laravel Facades help you keep you code simple and still testable since you can mock facades however might be a bit harder to tell a controllers dependencies if you use facades since they are probably all over the place in your code.
With dependency injection you need to write a bit more code since you need to deal with creating interfaces and services to handle the depenancies however Its a lot more clear later on what a controller depends on since these are clearly mentioned in the controller constructor.
I guess it's a matter of deciding which method you prefer using

What is the right granularity for dependencies while doing constructor or setter injection?

I am trying to define some dependency injection guidelines for myself. What should be the right granularity while defining dependencies for a class that are to be injected either via constructor or setter injection? The class could be a service, repository, etc. Suppose there is a repository class, which looks like following:
public class ProductRepository
{
//Option-A
public ProductRepository(DataSource dataSource)
{
}
//Option-B
public ProductRepository(SqlSession sqlSession)
{
}
//Option-C
public ProductRepository(SqlSessionTemplate sqlSessionTemplate)
{
}
}
The minimum dependency required by the above class is DataSource interface. The repository class internally makes use of the SqlSessionTemplate (implementation of the SqlSession interface). As shown in the code, there are 3 choices for constructor for doing constructor injection. The following is my understanding:
Option-A (DataSource dependency)
This is the minimum dependency of the repository class. From consumer point of view this constructor is the right choice but it is not suitable from unit testing point of view because DataSource is internally consumed by the SqlSessionTemplate in the repository implementation.
Options-B (SqlSession dependency)
This is the right choice from unit testing point of view but not from the consumer point of view. Additionally the repository implementation is tightly coupled with specific implementation of the interface which is SqlSessionTemplate. Hence it will not work if the consumer passes some different SqlSession interface other than SqlSessionTemplate.
Options-C (SqlSessionTemplate dependency)
SqlSessionTemplate being an implementation and not an interface does not seem to be good for unit testing. Also, it is not good for the consumer as instantiating SqlSessionTemplate is more involved as compared to DataSource. Hence discarding this option.
Option-A and Option-B seems to be the available choices. But, there is a trade-off between consumer point of view and unit testing point of view and vice versa.
I am new to dependency injection. I seek advice from the DI experts. What is the right solution (if any)? What would you do in the above situation?
Thanks.
This is the minimum dependency of the repository class.
I think this is the starting point for figuring out the right amount of coupling. You should be injecting no more or less than is needed to fulfill the requirements.
That's a very general guideline, which is almost the equivalent of "it depends", but it's a good way to start thinking about it. I don't know enough about DataSource, SqlSession, or SqlSessionTemplate to answer in context.
The repository class internally makes use of the SqlSessionTemplate
(implementation of the SqlSession interface)
Why can't the repository simply use the interface as a dependency? Does the interface not cover all the public methods of the implementation? If it doesn't, is the interface even a useful abstraction?
I can't completely piece together what you are trying to do and how the dependencies work, but my best guess is either:
You need both SqlSession and DataSource injected via the constructor, or
You need SqlSession injected via the Repository's constructor, and DataSource injected into the SqlSessionTemplate's constructor
You are talking about unit testing your repository, but that would typically be rather useless because a repository is your gateway to the database and has a strong coupling with it. Unit testing should be done in isolation, but a repository can only be tested with the database. Thus: an integration test.
If you were able to abstract the database specific logic from the repository (as you seem to be doing) there would be nothing left to test, since the responsibility of the repository is to communicate with the database. And if there still IS a lot left to test, well... in that case your repository classes are probably violating the Single Responsibility Principle, which makes your repositories hard to maintain.
So since you would typically test a repository itself using a database, from a testing perspective it doesn't really matter what you inject, since you will have to construct an repository in such way that it will be able to connect to a database anyway.

DI: When to list dependencies as params in ctor and when to call Container.Resolve<>()?

I use DI quite a lot in my projects and I'm fairly comfortable with the concept, however there's one aspect which I'm not quite sure about.
So a common use-case for me is to have an ASP.NET MVC Controller where I list the controller's dependencies in the constructor's parameter list, obviously these are passed in when the Controller is constructed by the DI Container, I then assign these to readonly private variables to be later consumed by Actions within the Controller.
Now, my concern is that if I only use an injected dependency (let's say an IMemberRepository) within one Action (and let's say there are 5 other Actions), should I list this as a dependency in the ctor, or should I call Container.Resolve<IMemberRepository>() within the one Action where it's used?
I have to say, I do like listing all my dependencies in the ctor, and I don't particularly like Container.Resolve<>() strewn throughout my code, but, going on the example above, there's no point in getting the DI container to instantiate an IMemberRepository if it's going to be used!
You should never call Container.Resolve from within your application code. This is the Service Locator pattern, and is considered an anti-pattern. Not injecting all dependencies through the constructor means you are hiding the used dependencies, which makes it less clear what depenencies a class has and makes it harder to test that class.
You are concerned about performance when dependencies are injected but not used, but this is normally not an issue, since construction of objects is usually very fast (since all those objects should do during construction is storing all incoming dependencies in private fields). When construction is proven to be too slow for a certaintype, there are other solutions, such as wrapping that dependency into a proxy that lazily initializes that dependency.
If you find that your class gets too many constructor arguments, it is a sign that it has too many responsibilities; it is doing too much. Try to repair this flaw in the class's design instead of falling back to Container.Resolve. For instance, extract a group of dependencies with the classes logic into a single new type and inject that as dependency.
There could be other problems with the design. When your controller depends directly on a repository dependency and you have business logic in the controller, you are missing an abstraction. You are missing a service layer. A good solution is the introduction of command handlers and query handlers.
I second what Steven has said.
If too many constructor arguments bug you then you could also opt for property injection. I favour this approach. There are some objects that, for some or other reason, are not injected into properties if they are not yet fully populated whereas they will be injected into the constructor.
I apply a guard to the dependency on properties to throw an exception if a dependency is null so that I know which dependency it is.
Hope that makes sense.
I would say that it depends on what you are wanting to do with DI.
The approach of using the injected dependencies as parameter in the constructor can end in a very long list of parameters.
This may be necessary for real Test Driven Development where you may want to mock the methods for your injected dependencies.
I personally think that it produces a lot of overhead as the DI Container always has to construct all dependencies, needed in an Action or not.
It is also to be considered that the usage of Actions and PartialViews produce a lot more constructions.
E.g.
public class HomeController : Controller
{
private IMemberRepository _memberRepo = null;
public HomeController(IMemberRepository repo)
{
_memberRepo = repo;
}
public ActionResult Index()
{
MyViewModel viewModel = _memberRepo.DoSomething();
return View(viewModel);
}
[ChildActionOnly]
public PartialViewResult SomePartialAction()
{
return PartialView();
}
}
Where the view Index.cshtml calls the partial view SomePartialAction() by #Html.Action("SomePartialAction").
In this case the constructor of the controller is called twice. Each time for each action. Therefore the DI container is also called twice.
So it really depends. For "hardcore" TDD you have to use the constructor. Otherwise I would resolve the dependencies where and when needed.

How do I resolve Dependency Injection in MVC Filter attributes

I have a custom attribute class derived from AuthorizationAttribute, which performs custom security on controller actions. The OnAuthorizationCore method depends on various other components (e.g. DAL) in order to ajudicate whether a user can invoke an action.
I'm using Autofac for dependency injection. The ExtensibleActionInvoker claims to be able to perform property injection on action filters. Setting an attribute's properties at runtime (which seems like a bad idea) will work in a simple unit test, but in a busy, multi-threaded web server it's bound to go wrong, and so this idea seems like an anti-pattern. Hence this question:
If my AuthorizationAttribute depends on other components in order to work correctly, what it the right [architecture] pattern in order to achieve this?
i.e. AuthorizationAttribute depends on IUserRepository... how should this relationship be resolved?
The ExtensibleActionInvoker claims to be able to perform property injection on action filters.
Correct - but don't confuse action filters with the attributes that might not implement them. The cleanest way to approach this in ASP.NET MVC is to split responsibilities, even though the MVC framework allows you to combine them.
E.g., use a pair of classes - an attribute class that holds data only:
// Just a regular old attribute with data values
class SomeAttribute : Attribute { ... }
And a filter that has dependencies injected:
// Gets dependencies injected
class SomeFilter : IActionFilter { ... }
SomeFilter just uses the typical approach of getting the SomeAttribute attribute from the controller or action method via GetCustomAttributes() to do whatever work is needed.
You can then use ExtensibleActionInvoker to wire up the filter:
builder.RegisterControllers(...).InjectActionInvoker();
builder.RegisterType<ExtensibleActionInvoker>().As<IActionInvoker>();
builder.RegisterType<SomeFilter>().As<IActionFilter>();
It might be a little more code than you'd write using the attribute-as-filter approach, but the quality of the code will be better in the long run (e.g. by avoiding the limitations of attributes and the awkwardness of the Service Locator solutions.)
I would seem that the easiest way to achieve this is to bite the bullet and accept a dependency on autofac itself. While a dependency on the IoC is in itself an anti-pattern, it's somewhat more pallatable. You can implement a property as follows:
public class UserAuthorizeAttribute : AuthorizeAttribute
{
public IUserRepository CurrentUserService
{
get
{
var cpa = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
var cp = cpa.ContainerProvider;
return cp.RequestLifetime.Resolve<IUserRepository>();
}
}
}
...
There's no straight-forward way to do this prior to MVC2. There is an interesting technique detailed here: http://www.mattlong.com.au/?p=154. I'd suggest using the Common Service Locator to abstract over this and locate your DI container.
If you're using MVC 3 then you can use MVC Service Location
Constructor injection seems to be impossible w/o changing way of filter registration.
Even in Asp.Net Mvc3:
One place where dependency injection has been difficult in the past is inside the filter attributes themselves. Because the .NET framework runtime is actually responsible for creating these attribute instances, we cannot use a traditional dependency injection strategy.
So - next best thing is property injection (Mvc3 provides some support for that out of the box).
Here's a how to for doing that manually.
I personally use MvcExtensions. I'm fine with registering them in different way. Here's usage.
Another thing You might want to investigate is MvcTurbine project. In contrast to MvcExtensions project which is more general - MvcTurbine is primarily for providing dependency injection support.

Repository Pattern in asp.net mvc with linq to sql

I have been reading though the code of the NerdDinner app and specifically the Repository Pattern...
I have one simple question though, regarding this block
public DinnersController()
: this(new DinnerRepository()) {
}
public DinnersController(IDinnerRepository repository) {
dinnerRepository = repository;
}
What if each Dinner also had, say, a Category... my question is
Would you also initialize the category Repository in the constructor of the class??
Im sure it would work but Im not sure if the correct way would be to initialize the repository inside the method that is going to use that repository or just in the constructor of the class??
I would appreciate some insight on this issue
Thanks.
What you're looking at here is actually not so much to do with the repository pattern, per se, and more to do with "dependency injection," where the outside things on which this class depends are "injected" from without, rather rather than instantiated within (by calling new Repository(), for example).
This specific example shows "constructor injection," where the dependencies are injected when the object is created. This is handy because you can always know that the object is in a particular state (that it has a repository implementation). You could just as easily use property injection, where you provide a public setter for assigning the repository or other dependency. This forfeits the stated advantage of constructor injection, and is somewhat less clear when examining the code, but an inversion-of-control container can handle the work of instantiating objects and injecting dependencies in the constructor and/or properties.
This fosters proper encapsulation and improves testability substantially.
The fact that you aren't instantiating collaborators within the class is what improves testability (you can isolate the behaviour of a class by injecting stub or mock instances when testing).
The key word here when it comes to the repository pattern is encapsulation. The repository pattern takes all that data access stuff and hides it from the classes consuming the repository. Even though an ORM might be hiding all the actual CRUD work, you're still bound to the ORM implementation. The repository can act as a facade or adapter -- offering an abstract interface for accessing objects.
So, when you take these concepts together, you have a controller class that does not handle data access itself and does not instantiate a repository to handle it. Rather the controller accepts an injected repository, and knows only the interface. What is the benefit? That you can change your data access entirely and never ever touch the controller.
Getting further to your question, the repository is a dependency, and it is being provided in the constructor for the reasons outlined above. If you have a further dependency on a CategoryRepository, then yes, by all means inject that in the constructor as well.
Alternatively, you can provide factory classes as dependencies -- again classes that implement some factory interface, but instead of the dependency itself, this is a class that knows how to create the dependency. Maybe you want a different IDinnerRepository for different situations. The factory could accept a parameter and return an implementation according to some logic, and since it will always be an IDinnerRepository, the controller needs be none the wiser about what that repository is actually doing.
To keep your code decoupled and your controllers easily testable you need to stick with dependency injection so either:
public DinnersController()
: this(new DinnerRepository(), new CategoryRepository()) {
}
or the less elegant
public DinnersController()
: this(new DinnerRepository(new CategoryRepository())) {
}
I would have my dinner categories in my dinner repository personally. But if they had to be seperate the id put them both in the ctor.
You'd want to pass it in to the constructor. That said, I probably wouldn't create any concrete class like it's being done there.
I'm not familiar with the NerdDinner app, but I think the preferred approach is to define an IDinnerRepository (and ICategoryRepository). If you code against interfaces and wanted to switch to say, an xml file, MySQL database or a web service you would not need to change your controller code.
Pushing this out just a little further, you can look at IoC containers like ninject. The gist of it is is that you map your IDinnerRepository to a concrete implementation application wide. Then whenever a controller is created, the concrete repository (or any other dependency you might need) is provided for you even though you're coding against an interface.
It depends on whether you will be testing your Controllers (, which you should be doing). Passing the repositories in by the constructor, and having them automatically injected by your IOC container, is combining convenience with straightforward testing. I would suggest putting all needed repositories in the constructor.
If you seem to have a lot of different repositories in your constructors, it might be a sign that your controller is trying to do too many unrelated things. Might; sometimes using multiple repositories is legitimate.
Edit in response to comment:
A lot of repositories in one controller constructor might be considered a bad code smell, but a bad smell is not something wrong; it is something to look at because there might be something wrong. If you determine that having these activities handled in the same controller makes for the highest overall simplicity in your solution, then do that, with as many repositories as you need in the constructor.
I can use myself as an example as to why many repositories in a controller is a bad smell. I tend to get too cute, trying to do too many things on a page or controller. I always get suspicious when I see myself putting a lot of repositories in the constructor, because I sometimes do try to cram too much into a controller. That doesn't mean it's necessarily bad. Or, maybe the code smell does indicate a deeper problem, but it not one that is too horrible, you can fix it right now, and maybe you won't ever fix it: not the end of the world.
Note: It can help minimize repositories when you have one repository per Aggregate root, rather than per Entity class.

Resources