Dependancy issue with static utility classes with repository (.NET MVC project) - asp.net-mvc

I have an MVC project with the standard IoC setup that uses StructureMap to inject repositories into controller constructors.
I also decided I wanted to have a static "utilities" class where I could have common methods that can be called by different controllers. So for example, I have:
public static IEnumerable<CountryCode> GetCountryList()
{
ICountryCodeRepository repo = ObjectFactory.GetInstance<ICountryCodeRepository>();
IEnumerable<CountryCode> countries = repo.GetAll();
return countries;
}
As you can see, that directly creates a repo object from the ObjectFactory. The problem, now, is that when I want to unit-test my controllers, I can mock the repos for the controllers, but not the repos in the utilities class (which the controller eventually calls) I'm sure there are other reasons why my utilities class is wrong, but this is what I see so far. I've also read some stuff saying what I have is bad design, I just don't know how to fix it.
I was thinking about having the GetCountryList() function to accept a repo object
GetCountryList(ICountryCodeRepository _repo)
and the calling controller would pass it in, but isn't that just creating another dependency concern because all controllers will have to know what the utility functions need?
Or is it possible to use StructureMap somehow to inject these utility methods?

It's at least OK that you know that what you are doing is bad design. That's fine and people reading this post will know it as well and avoid doing the same mistake as you.
But now to the point, you could use a provider in your static class:
public static class Foo
{
public static Func<ICountryCodeRepository> CountryRepoProvider =
() => ObjectFactory.GetInstance<ICountryCodeRepository>();
public static IEnumerable<CountryCode> GetCountryList()
{
return CountryRepoProvider().GetAll();
}
}
and now in your unit test you could mock it:
Foo.CountryRepoProvider = () => mocha;
or if you are using ASP.NET MVC 3 and you DI framework uses a dependency resolver you could improve this code by at least making it DI framework agnostic:
public static IEnumerable<CountryCode> GetCountryList()
{
var repo = DependencyResolver.Current.GetService<ICountryCodeRepository>();
return repo.GetAll();
}
Now in your unit test you could of course write a custom dependency resolver which will spit mocked instances of your services.
And now when you look at this code you might really say to yourself: What am I doing? I am writing a static class with one liner methods delegating to a repository I am fetching from the DI. What's the point when I can benefit from my DI framework to directly inject the instance of this repository wherever I need it and then simply call the method I need on it? What am I unit testing in those one liner static methods? Why am I wasting my time.
And if of course you had more complex logic to handle you would simply write a service layer which will take the necessary repositories as constructor dependencies and perform the complex business operations on them. Then you will simply configure your DI framework to inject those ready to be used instance of the service in your controllers or wherever you need it. See? No need of any static class. Weak coupling and unit testing friendly code.

Related

Implementing Dependency Injection in a Controller to create loosly couple system

I have a HomeController and a Referrence of a type-class.If I create a new object of the class it works fine for me. But I dont want to create new object in the Controller instead I want to pass a referrence of the class through the HomwController's Constructor.Here is my code. I need to implement DI here.
//private readonly UnitOfWork<Student> _unitOfWork = new UnitOfWork<Student>();
private readonly UnitOfWork<Student> _unitOfWork;
//TODO ??
public HomeController(UnitOfWork<Student> unitOfWork)
{
_unitOfWork = unitOfWork;
}
public ActionResult Index()
{
return View(_unitOfWork.GenericRepository.GetAll());
}
Any help?
First, if you want to use dependency injection, you'll have to go through a third party dependency injection container - NInject or Unity for example among many others (or building your own if you are looking for some challenge).
Second, your HomeController should take an abstract unit of work type (interface or abstract class) as a parameter. You are actually using a concrete type in your HomeController constructor which is not how things should work in a dependency injection world (when using "Constructor Injection", your dependency container is in charge of providing the concrete implementation for the abstraction, based on container configuration).
Third your UnitOfWork<Student> does not make a lot of sense. A Repository<Student> would make some sense, but a Unit Of Work is not working on a single "Type" but rather on a "collection" of different data sets (a unit of work is potentially working on a collection of repositories). What would make sense here is to specify a parameter IUnitOfWork unitOfWork in your HomeController constructor, and configure your depency container to pass in a concrete UnitOfWork object on which you can get your Repository<Student> do operations on it in your action method (and potentially on other repositories accessed from the UnitOfWork object) and then Commit all modifcations by calling the associated method on the UnitOfWork object.
You should make some searches arround NInject use with ASP.NET MVC3 and also take a look at EntityFramework if you are dealing with UnitOfWork and Repository patterns (and if data is backed by a DB).
EDIT
In reaction to your comment dealing with (IUnitOfWork<Student> and IUnitOfWork<Course>).
As I said before, it does not make a lot of sense :
A UnitOfWork can be grossly seen as a "container" of repositories, giving access to these repositories and coordinating actions (like commiting all the changes) on these repositories. You should rather have an abstract non generic type IUnitOfWork, providing access to generic repositories such as IRepository<Student> or IRepository<Course>, and also containing a Commit method which would commit to DB (or file, or memory or whatever the unitofwork/repository implementation is targeting to persist data).
This way instead of injecting an IRepository<Student> and/or IRepository<Course> in your controller constructor (or if your controller needs to work on 10 different repositories, well, pass 10 parameters :S), you just accept a single parameter of abstract type IUnitOfWork (the concrete instance being injected by the DI container), and then any action method can work on any set of repository by getting them from the UnitOfWork, and once it has done all the changes, it can call Commit on the unitOfWork which will take care of comming all the modifications that have been done in the repository.
That's the theory and the general idea.
Now more specifically about DI in ASP.NET MVC, the more common way (there are other ways) of "plumbing" the DI container is to create a class inheriting from IDependencyResolver making use of the DI container to resolve types, and in Application_Start call DependencyResolver.SetResolver whith an instance of this class.
This way, when ASP.NET MVC is asked to create a controller (end user request), it will go through this depency resolver to ask for an instance of the controller, and this dependency resolver will turn to the DI container to create an instance of the controller by taking care of all needed injection.
You should take a look on the website / forums of your specific DI container as they all show ways to plumb it with ASP.NET MVC.
This is just a very high overview, there are a lot of tricky details, but that's the gross idea.
EDIT2
Just posted an article (my first one) on my blog to explain how to correctly use the Repository and UnitOfWork patterns in an ASP.NET MVC project.
http://codefizzle.wordpress.com/2012/07/26/correct-use-of-repository-and-unit-of-work-patterns-in-asp-net-mvc/
Are you talking ASP.NET MVC ?
I have been working with Ninject for some time now, and am very happy with it! Take a look at the sample app in this repository to get an idea on how to use it in ASP.NET MVC 3:
https://github.com/ninject/ninject.web.mvc/tree/master/mvc3
To expand a bit on the reply, here's a code snippet from where I set up the Ninject bindings
kernel.Bind(typeof(IUnitOfWork<>).To(typeof(UnitOfWork<>));
And my controller:
public class MyController : Controller {
private readonly IUnitOfWork<Student> uowStudent;
public MyController(IUnitOfWork<Student> uowStudent) {
this.uowStudent = uowStudent;
}
}
Then all you need to do, is make sure any arguments in the constructor for the UnitOfWork class are also bound in the kernel.

DDD and constructor explosion

I'm practicing DDD with ASP.NET MVC and come to a situation where my controllers have many dependencies on different services and repositories, and testing becomes very tedious.
In general, I have a service or repository for each aggregate root. Consider a page which will list a customer, along with it's orders and a dropdown of different packages and sellers. All of those types are aggregate roots. For this to work, I need a CustomerService, OrderService, PackageRepository and a UserRepository. Like this:
public class OrderController {
public OrderController(Customerservice customerService,
OrderService orderService, Repository<Package> packageRepository,
Repository<User> userRepository)
{
_customerService = customerService
..
}
}
Imagine the number of dependencies and constructor parameters required to render a more complex view.
Maybe I'm approaching my service layer wrong; I could have a CustomerService which takes care of all this, but my service constructor will then explode. I think I'm violating SRP too much.
I think I'm violating SRP too much.
Bingo.
I find that using a command processing layer makes my applications architecture cleaner and more consistent.
Basically, each service method becomes a command handler class (and the method parameters become a command class), and every query is also its own class.
This won't actually reduce your dependencies - your query will likely still require those same couple of services and repositories to provide the correct data; however, when using an IoC framework like Ninject or Spring it won't matter because they will inject what is needed up the whole chain - and testing should be much easier as a dependency on a specific query is easier to fill and test than a dependency on a service class with many marginally related methods.
Also, now the relationship between the Controller and its dependencies is clear, logic has been removed from the Controller, and the query and command classes are more focused on their individual responsibilities.
Yes, this does cause a bit of an explosion of classes and files. Employing proper Object Oriented Programming will tend to do that. But, frankly, what's easier to find/organize/manage - a function in a file of dozens of other semi-related functions or a single file in a directory of dozens of semi-related files. I think that latter hands down.
Code Better had a blog post recently that nearly matches my preferred way of organizing controllers and commands in an MVC app.
Well you can solve this issue easily by using the RenderAction. Just create separate controllers or introduce child actions in those controllers. Now in the main view call render actions with the required parameters. This will give you a nice composite view.
Why not have a service for this scenario to return a view model for you? That way you only have one dependency in the controller although your service may have the separate dependencies
the book dependency injection in .net suggests introducing "facade services" where you'd group related services together then inject the facade instead if you feel like you have too many constructor parameters.
Update: I finally had some available time, so I ended up finally creating an implementation for what I was talking about in my post below. My implementation is:
public class WindsorServiceFactory : IServiceFactory
{
protected IWindsorContainer _container;
public WindsorServiceFactory(IWindsorContainer windsorContainer)
{
_container = windsorContainer;
}
public ServiceType GetService<ServiceType>() where ServiceType : class
{
// Use windsor to resolve the service class. If the dependency can't be resolved throw an exception
try { return _container.Resolve<ServiceType>(); }
catch (ComponentNotFoundException) { throw new ServiceNotFoundException(typeof(ServiceType)); }
}
}
All that is needed now is to pass my IServiceFactory into my controller constructors, and I am now able to keep my constructors clean while still allowing easy (and flexible) unit tests. More details can be found at my blog blog if you are interested.
I have noticed the same issue creeping up in my MVC app, and your question got me thinking of how I want to handle this. As I'm using a command and query approach (where each action or query is a separate service class) my controllers are already getting out of hand, and will probably be even worse later on.
After thinking about this I think the route I am going to look at going is to create a SerivceFactory class, which would look like:
public class ServiceFactory
{
public ServiceFactory( UserService userService, CustomerService customerService, etc...)
{
// Code to set private service references here
}
public T GetService<T>(Type serviceType) where T : IService
{
// Determine if serviceType is a valid service type,
// and return the instantiated version of that service class
// otherwise throw error
}
}
Note that I wrote this up in Notepad++ off hand so I am pretty sure I got the generics part of the GetService method syntactically wrong , but that's the general idea. So then your controller will end up looking like this:
public class OrderController {
public OrderController(ServiceFactory factory) {
_factory = factory;
}
}
You would then have IoC instantiate your ServiceFactory instance, and everything should work as expected.
The good part about this is that if you realize that you have to use the ProductService class in your controller, you don't have to mess with controller's constructor at all, you only have to just call _factory.GetService() for your intended service in the action method.
Finally, this approach allows you to still mock services out (one of the big reasons for using IoC and passing them straight into the controller's constructor) by just creating a new ServiceFactory in your test code with the mocked services passed in (the rest left as null).
I think this will keep a good balance out the best world of flexibility and testability, and keeps service instantiation in one spot.
After typing this all out I'm actually excited to go home and implement this in my app :)

Implementing the Repository Pattern in ASP.NET MVC

I am still having a hard time wrapping my head around this. I want to separate my layers (dlls) like so:
1) MyProject.Web.dll - MVC Web App (Controllers, Models (Edit/View), Views)
2) MyProject.Services.dll - Service Layer (Business Logic)
3) MyProject.Repositories.dll - Repositories
4) MyProject.Domain.dll - POCO Classes
5) MyProject.Data.dll - EF4
Workflow:
1) Controllers call Services to get objects to populate View/Edit Models.
2) Services call Repositories to get/persist objects.
3) Repositories call EF to get/persist objects to and from SQL Server.
My Repositories return IQueryable(Of T) and inside them they utilize ObjectSet(Of T).
So as I see this, the layers depend on exactly the next layer down and the lib that contains the POCO classes?
A few concerns:
1) Now for my Repositories to work correctly with EF, they will depend on System.Data.Objects, now I have a tight coupling with EF in my repository layer, is that bad?
2) I am using the UnitOfWork pattern. Where should that live? It has a Property Context As ObjectContext, so that is tightly coupled to EF as well. Bad?
3) How can i use DI to make this easier?
I want this to be a loosely coupled as possible for testing. Any suggestions?
---------- Edit ----------
Please let me know if I am on the right track here. Also, so the Service gets injected with an IRepository(Of Category) right, how does it know the difference between that and the concrete class of EFRepository(Of T)? Same with the UnitOfWork and the Service?
Once someone helps me figure this out to where I understand it, I know it will have seemed trivial, but man I am having a heck of a time wrapping my head around this!!
Controller
Public Class CategoryController
Private _Service As Domain.Interfaces.IService
Public Sub New(ByVal Service As Domain.Interfaces.IService)
_Service = Service
End Sub
Function ListCategories() As ActionResult
Dim Model As New CategoryViewModel
Using UOW As New Repositories.EFUnitOfWork
Mapper.Map(Of Category, CategoryViewModel)(_Service.GetCategories)
End Using
Return View(Model)
End Function
End Class
Service
Public Class CategoryService
Private Repository As Domain.Interfaces.IRepository(Of Domain.Category)
Private UnitOfWork As Domain.Interfaces.IUnitOfWork
Public Sub New(ByVal UnitOfWork As Domain.Interfaces.IUnitOfWork, ByVal Repository As Domain.Interfaces.IRepository(Of Domain.Category))
UnitOfWork = UnitOfWork
Repository = Repository
End Sub
Public Function GetCategories() As IEnumerable(Of Domain.Category)
Return Repository.GetAll()
End Function
End Class
Repository and UnitOfWork
Public MustInherit Class RepositoryBase(Of T As Class)
Implements Domain.Interfaces.IRepository(Of T)
End Class
Public Class EFRepository(Of T As Class)
Inherits RepositoryBase(Of T)
End Class
Public Class EFUnitOfWork
Implements Domain.Interfaces.IUnitOfWork
Public Property Context As ObjectContext
Public Sub Commit() Implements Domain.Interfaces.IUnitOfWork.Commit
End Sub
End Class
Original Answer
No. However, to avoid coupling the Services to this, have an ISomethingRepository interface in your domain layer. This will be resolved by your IoC container.
The Unit of Work patterns should be implemented with your Repositories. Use the same solution to decoupling this as I suggested with decoupling your repositories from your services. Create an IUnitOfWork or IUnitOfWork<TContext> in your domain layer, and put the implementation in your Repository layer. I don't see any reason that your repository implementation needs to be separate from your Data layer, if all the Repositories do is persist data to the ObjectContext in data layer. The Repository interface is domain logic, but the implementation is a data concern
You can use DI to inject your services into the controllers and your repositories into your services. With DI, your service will have a dependency on the repository interface ISomethingRepository, and will receive the implementation of the EFSomethingRepository without being coupled to the data/repository assembly. Basically, your IControllerFactory implementation will get the IoC container to provide all the constructor dependencies for the Controller. This will require that the IoC container also provides all the controllers' constructor dependencies (service) their constructor dependencies (repositories) as well. All of your assemblies will have a dependency on your domain layer, (which has the repository and service interfaces), but will not have dependencies on each other, because they are dependent on the interface and not the implementation. You will either need a separate assembly for the Dependency Resolution or you will need to include that code in your Web project. ( I would recommend a separate assembly). The only assembly with a dependency on the Dependency Resolution assembly will be the UI assembly, although even this is not completely necessary if you use an IHttpModule implementation to register your dependencies at the Application_Start event (the project will still need a copy of the dll in your bin folder, but a project reference is not necessary). There are plenty of suitable open source IoC containers. The best one depends a lot on what you choose. I personally like StructureMap. Both it, and Ninject are reliable and well documented DI frameworks.
Response to Sam Striano's Edits
It's been years since I've coded in VB so my syntax may be off.
Public Class CategoryController
Private _Service As Domain.Interfaces.IService
'This is good.
Public Sub New(ByVal Service As Domain.Interfaces.IService)
_Service = Service
End Sub
Function ListCategories() As ActionResult
Dim Model As New CategoryViewModel
Using UOW As New Repositories.EFUnitOfWork
This doesn't need to be in the controller. Move it into the Repository and have it surround the actual transaction. Also, you don't want your controller to have a dependency on the data layer.
Mapper.Map(Of Category, CategoryViewModel)(_Service.GetCategories)
Is this a call to AutoMapper? Not related to your original question, but, you should relocate the mapping functionality to an ActionFilter so your return is just Return View(_Service.GetCategories)
End Using
Return View(Model)
End Function
The Service class had no problems.
The Repository and Unit of Work look mostly incomplete. Your Repository should new up the ObjectContext and inject it into the Unit of Work, then execute all transactions in the scope of the Unit of Work (similar to what you did in the controller). The problem with having it in the Controller is it's possible that a single Service call could be scoped to multiple units of work. Here is a good article on how to implement Unit of Work. http://martinfowler.com/eaaCatalog/unitOfWork.html. Martin Fowler's books and website are great sources of information on these types of topics.
To answer your concerns in order
1) Not necessarily bad, kind of depends on how likely you are to stick with EF. There are several things you could do to reduce this. One relatively low cost (assuming you have some Inversion of Control setup, if not skip to 3) is to only reference interfaces of your repositories from your services.
2) Same again, I think you could spend a lot of time not making your application not coupled to EF but you have to ask yourself if this change of direction would not make for other changes as well. Again, a layer of indirection could be brought in through interfacing and easily swap out one repository implementation with another later.
3) Inversion of Control should again allow all the testing you'd want. Thus no need for many direct references at all and to test any layer in isolation.
UPDATE for requested sample.
public class QuestionService : IQuestionService
{
private readonly IQuestionRepository _questionRepository;
public QuestionService(IQuestionRepository questionRepository){
_questionRepository = questionRepository
}
}
Thus your service only knows of an interface which can be mocked or faked within your unit tests. It is all pretty standard IoC stuff. There is lots of good reference out there on this, if a lot of this is new to you then I'd recommend some a book to give you the full story.
I would suggest using MEF. It gives you the dependency injection framework you want but it isn't full-fledged; it's excellent for unit test. Here are a few answers to a related question: Simplifying Testing through design considerations while utilizing dependency injection
Full code exmple can be found here with MEF and Repository Pattern (also uses EFCodeFirst).

ASP.NET MVC Configuration Class using IoC

In an MVC app, we the have need to create a configuration settings class that is needed throughout the app. It is a cross-cutting concern in that it is need in controllers, sometimes deep in the domain logic, as well as place like HtmlHelper extensions. The fact that it's needed is so many different places is what is tripping me up.
The class will wrap settings that are pulled from the web.config, as well as a table in a DB. The DB settings query will be cached so I'm not worried about that getting hit up for every request.
In years past I may have created some static type of class or singleton, but I don't want to lose the testability I have now. What would be the best way to instantiate this class and then to be able to access it through pretty much anywhere in the app?
I would continue to use a singleton. But a singleton which is wrapping an interface, which also makes it testable.
public class Configuration
{
private IConfiguration _config;
public static IConfiguration Instance { get { return _config; }}
public static void Assign(IConfiguration config)
{
_config = config;
}
}
Simply use Assign in global.asax or any of your unit tests.
If you want to do it the correct way, you should provide the configuration settings directly in the constructors of your objects.
Instead of
public class MyService
{
public MyService()
{
var confString = Configuration.Instance.GetConnectionString()
}
}
You would do:
public class MyService
{
public MyService(string confString)
{}
}
Finally, I would not have any configuration dependencies in HTML helpers. By doing so yuo are adding business logic to your views which breaks separation of concerns
I think the codeplex project mvccontrib provided some hooks to use
at least 3 IOC providers as far as I not windsor, structurmap, spring.net...
but I did not used it myself
you can find out more here
http://mvccontrib.codeplex.com/
and maybe you can look into the sourcecode of this project and see where you can go from there...
HTH
I would refactor my app not to use configuration everywhere. I use configuration in controllers only. My views do not have any logic, my domain model does just have business logic, not application logic.

What design pattern to locate my IUnitOfWork?

I've implemented a repository pattern with persistence ignorance. The repository implementation only interacts with my entity objects, IUnitOfWork and ITable<T> interfaces. The intention is that the IUnitOfWork isn't reused but represents a single transaction. So far, I've implemented in-memory as well as Linq-to-Sql versions of the IUnitOfWork and ITable<T>.
My problem is that due to the IUnitOfWork injection into the repository, I end up with needing to know how to instantiate a new IUnitOfWork where ever the repository is used. Since this is the primary piece that is supposed to be pluggable it feels like I've done something wrong. The general usage pattern is something like this:
FooUnitOfWork unitOfWork = new FooUnitOfWork();
Repository repos = new Repository(unitOfWork);
// ...act upon repos
unitOfWork.Save();
Now it appears that I need some other pattern to allow every repository usage in the app to obtain the correct unit of work (e.g. in-memory, L2S, etc.).
What is the most fitting pattern for this? I've looked at Fowler's discussion on the topic but none of his examples seem to be a clean fit. I already feel like the amount of abstraction that I have is more than I'd like so building yet another indirection seems excessive.
At the moment, I'm leaning toward some sort of app-wide provider which can be configured to produce the correct IUnitOfWork. Am I off-base or is this what is needed to truly be implementation agnostic?
Update: while this didn't really break down it ended up just producing a poor-man's IoC Container. I ended up just replacing all of these:
UnitOfWorkFactory.Create();
with the generalized Common Service Locator implementation:
Microsoft.Practices.ServiceLocation.ServiceLocator.Current.GetInstance<IUnitOfWork>();
This allowed me to create a library which uses Dependency Injection without forcing all users to use the same IoC framework.
Perhaps I should use a very simple factory where I can set a callback? It could have a set of static methods on it like this:
public static class UnitOfWorkFactory
{
private static Func<IUnitOfWork> FactoryMethod;
public static IUnitOfWork Create()
{
if (UnitOfWorkFactory.FactoryMethod == null)
{
throw new InvalidOperationException("...");
}
return UnitOfWorkFactory.FactoryMethod();
}
public static void SetFactoryMethod(Func<IUnitOfWork> factory)
{
UnitOfWorkFactory.FactoryMethod = factory;
}
}
Where does this break down?
I would suggest using a Vistor pattern to discover the implementations of the IUnitOfWork interface.
[UnitOfWork(Name="foo")]
public class FooUnitOfWork : IUnitOfWork {}
Repository repo = new Repository("foo");
//stuff happens
repo.Save(); //or repo.Worker.Save();
Inside the repo instance a discovery factory finds the worker and creates it.

Resources