Where do I put my Ioc (ninject) code in my service layer project? - asp.net-mvc-2

I have 3 project files
webui - controllers and views
framework - service layer and repos
tests- unit tests
So how I see it is that my controllers will only talk to my service layer(that contains my business logic). The service layer will talk to the repos and get database data.
My repo will just talk do the database and return data.
Now if I want to unit test this I need to have fake service layers and fake repositories.
this way I can test the controllers in isolation and the service layers in isolation.
So where do I put my ninject code in my framework class library so that I can use it with my service layer?
Edit
Steven are you saying I should be doing something like this
//setup ninject in global aspx with mvc extension
// now bind the stuff
private class SportsStoreServices : NinjectModule
{
public override void Load()
{
Bind<IAdminService>().To<AdminService>();
Bind<IAdminRepo>().To<AdminRepo>();
}
}
// controller
public class AccountController : Controller
{
//
// GET: /Account/
private IAdminService adminService;
public AccountController(IAdminService adminService)
{
this.adminService = adminService;
}
public ActionResult Login()
{
var getAllAdmins = adminService.GetAllAdmins();
return View();
}
}
// Service Layer
public class AdminService : IAdminService
{
private IAdminRepo adminRepo;
public AdminService(IAdminRepo adminRepo)
{
this.adminRepo = adminRepo;
}
public List<Admins> GetAllAdmins()
{
return adminRepo.GetAllAdmins();
}
}
//Repo
public class AdminRepo : IAdminRepo
{
public List<Admins> GetAllAdmins()
{
// some query to get all admins
}
}

When you follow the Dependency Injection pattern correctly (and completely) the only place you need to reference your IoC container is in your application root (in your case your web project). For MVC you would typically have a ControllerFactory that knows how to create new controllers using your particular IoC framework. Your controllers will be designed around constructor injection so your IoC framework is able to automatically inject all the dependencies. You will typically use constructor injection throughout the whole project. This allows you to let the rest of your code stay ignorant of the choosen IoC implementation.
For unit tests you would normally use constructor injection to manually inject the dependencies. This saves you from having to configure your IoC framework for your unit tests. Using an IoC library in your test project is painful, because you often want different dependencies to be returned per test case and testing frameworks often run your tests in parallel. So best is to not use any IoC framework in your tests, but call the constructor of a type under test yourself.
The trick for unit tests with DI is to keep your unit tests maintainable. You can do this for instance, by extracting the creation of a type under test into a factory method. This allows you to call such a constructor just in one place in your code. When the constructor changes, you would will have to change your test code in one place. I learned a lot about writing maintainable unit tests by the book The Art of Unit Testing. I can recommend it.

At project the DI should be in the place where the object composition can Happen.. For instance in WCF service Project we can do it using IInstanceProvider,IN asp.net Global.asax .
Ground rule:Make sure the DI is the application start up point

Related

Unit of Work, Entity Framework DBContext Scope

I've run into a bit of a problem with EF looking for the best practice for this problem:
public void TestEntityFramework_UOWImplementation()
{
using (UnitOfWorkInventory uow = new UnitOfWorkInventory())
{
IMaterialRepository repos = new MaterialRepository(uow);
Material mat = GetMaterial("Mikes Material", 1);
mat.CostPrice = 20;
repos.InsertOrUpdate(mat);
uow.Commit();
}
}
private Material GetMaterial(string sku, int clientId)
{
IMaterialRepository repos = new MaterialRepository(new UnitOfWorkInventory();
return repos.Find(sku, clientId);
}
In the TestEntityFramework_UOWImplementation() method, its fine, i call create a scope for my unit of work.. and create a repository inside it.
But when i want to getMaterials() as below.. I have no access to the unit of work or the repository, unless i actually pass it as a parameter! This is clearly not particularly nice.
How do people get around this problem??
Thanks in advance!
Neil
In your implementation you wont have access to the Unit of Work like that. What I do is use an IoC container and Dependency Injection to handle it. I have a WCF service that uses Unit of Work with a repository pattern against EF5.
You can read more about repository pattern, unit of work, and EF here but basically what I do is in the constructor of my service class I inject the Unit of Work like so:
private readonly IUnitOfWork uow;
public LoanService(IUnitOfWork unitOfWork)
{
uow = unitOfWork;
}
Then I can use uow.WhateverMethod in my repos anywhere in the service. I use Ninject to handle the injection of IUnitOfWork. Hope it helps you.
If anyone was looking for a way around this, I done something a bit different.
I used a Dependency Injection framework (StructureMap) to handle all DI, so everytime i instantiate a repository it will retrieve the DBContext from the Service Locator of StructureMap. I also make the dbcontext scope to be for the duration of the request from the webserver.
The advantage here being that everytime i retrieve or inject a DBContext, it will retrieve the same context for the duration of the request meaning i can use this across multiple methods and class! I pass the interface type as a generic param to the constructor, meaning that i can point the repo as different contexts. Helpful in applications where there are lots of dbcontexts.
Repo Constructor Eg:
public class PurchaseOrderRepository<TDbContext> : GenericRepository<PurchaseOrder>, IPurchaseOrderRepository<TDbContext> where TDbContext : DbContext
{
public PurchaseOrderRepository()
: base((TDbContext)ObjectFactory.GetInstance<TDbContext>())
{
}
}
Usage:
//resolves the request scope InventoryContext...
var pRepos = new PurchaseOrderRepository<IInventoryContext>();
and the structure map dependency looks like:
For<IInventoryContext>().HttpContextScoped().Use<InventoryContext>();

.NET REST services, Entity Framework and loose coupling

I'm working on a web application project using ASP.NET MVC3 and database in SQL Server. There is also a mobile application that uses the data from the same database via REST services. Here are some of my application's layers:
Model - ADO.NET Data Model, using Entity Framework
Data Access Layer - Repositories with queries to retrive data from database
Web application - MVC3 project, using repositories, loose coupling using Structure Map and DI, database context gets disposed at the end of the HttpRequest
Core - another layer between DAL and Service Layer, uses Repositories and exposes data to Service Layer. Sort of Business Logic Layer.
Service Layer - REST services, knows about Core layer but not about DAL. Maps the data to DTOs and exposes to the client
The problem I've got with such application architecture is loose coupling on the Service Layer. Service Layer has reference to Core layer. Core layer has reference to Data Access Layer and uses its repositories. Repositories do not have a default constructor though. They expect 1 parameter and its database object context (disposable object).
Using repositories directly on my website is not a problem. I'm using Structure Map and DI makes it loosely coupled. Each context gets disposed at the end of the HttpRequest.
The problem is that Service Layer and Core layer. I'd like to have loose coupling there as well but not sure how to achieve it? How to inject data context into those and make sure it gets disposed at certain moment? I'd like to hear some suggestions on how to put it all together.
Service Layer has reference to Core layer.
That's fine.
Core layer has reference to Data Access Layer and uses its repositories.
That ain't fine.
Your "Core" should be your domain, with business rules and logic. It should not have any dependencies.
Start from the bottom of the stack:
Repo - no dependencies on other layers.
Services - dependency on Core and Repo.
Core - no dependencies on other layers.
Web - dependant on everything.
This is how we do it. We use a combination of interface-driven programming and dependency injection to handle the loose coupling.
Example flow:
HTTP Request comes in (API, web tier, etc)
Controller found. DI container sees container has dependancy on ISomethingService and resolves it, including any further down dependencies (service, repo, etc).
Controller calls method on ISomethingService.
ISomethingService implementation (chosen by DI) calls method on ISomeRepo.
ISomeRepo implementation (chosen by DI) calls EF/DB, returns "data-object" to service.
Service maps "data-object" to "Core" object and returns to controller.
The instantiation of these objects should be handled by your DI container. The only thing missing from the above which we use is a "Unit of Work", which essentially wraps the EF context.
public ServiceLayerClass()
{
private ICoreLayerClass coreLayerClass;
public ServiceLayerClass(ICoreLayerClass coreLayerClass)
{
this.coreLayerClass = coreLayerClass;
}
public void DoSomeWork()
{
coreLayerClass.DoSomeWork();
}
}
public CoreLayerClass()
{
private ISomeRepository someRepository;
public CoreLayerClass(ISomeRepository someRepository)
{
someRepository = this.someRepository;
}
public void DoSomeWork()
{
someRepository.DoSomeWork();
}
}
public SomeRepository()
{
public SomeRepository(IUnitOfWork uow)
{
}
public void DoSomeWork()
{
//do some work
}
}
Notes:
UnitOfWork would ideally be created per HttpContext. ie., your datacontext will begin its life at the beginning Request and will get disposed at the end. You will use only one per request.

Where does Unit Of Work belong w/ EF4, IoC (Unity), and Repository?

I see several questions relating somewhat to this, but I still can't find the answer I'm looking for, so I'm posting my question. If another question holds the answer (and I'm just not seeing it), please point me to it.
I'm trying to figure out where my UnitOfWork belongs -- and specifically, gets created -- when using EF4 and Unity with the Repository pattern.
Basically, I have a service that is used to implement my business logic. This service constructor takes in the repository, so the service gets injected with my repository. The service then uses the injected repository to carry out actions against the data store -- but I need to wrap these in a unit of work.
My unit of work, however, needs to be injected with the EF4 context (or, in my case, and interface of the context -- IObjectContext). And I'm not sure where the UoW should be created and injected w/ the context.
Here are the possible options I can think of, none of which seem ideal:
Include the UoW in the service constructor, thus having the service injected w/ the unit of work, which in turn is injected w/ my EF4 context. But this seems wrong because I don't want my UoW created on every instance of the repository.
Do an on-demand creation using container.Resolve to get an instance of the UoW, injecting my EF4 context. This seems excessive having to constantly hit the IoC container, rather than already having access to the UoW.
Inject the context directly into the service, allowing me to create a UoW(context). This seems bad since I've now exposed the context to the service, and this should be isolated to the repository.
So my question is, is one of these methods acceptable, or is there another method I'm not thinking of?
Thanks in advance.
There are probably several ways how to use this so I will describe one which I found useful.
Imho the place to define UoW is in Application logic - the logic which calls your business layer (business services). The reason for this is that UoW should represent logical business trasaction - application logic (or service facade in case of remote calls) defines what is logical transaction. So for example in MVC you can go with architecture where each controller action represents single UoW:
public class MyController : Controller
{
public MyController(IFirstService firstService, ISecondService secondService,
IUnitOfWork unitOfWork)
{ ... }
[HttpPost]
public ActionResult SomeAction(Model data)
{
_firstService.SomeProcessing(data);
_secondService.SomeProcessing(data);
_unitOfWork.SaveChanges();
return RedirectToAction(...);
}
}
In this example my controller is depenent on two business services and action calls them both - UoW then save changes performed by both services. That is the reason why I think the UoW should be available in controller because if your application layer don't have access to UoW you can't compose (reuse) your logic from several service calls (because each probably calls its own SaveChanges).
Other approach is with service facade. Facade will be public interface of your business layer and it will hide service composition:
_firstService.SomeProcessing(data);
_secondService.SomeProcessing(data);
_unitOfWork.SaveChanges();
In such case UoW will not be passed to controller but to service facade and service facade will be injected to controller. You will definitely use this approach if your business logic will be exposed over web service (or other remote technology).
The last problem which you have to deal with is passing UoW to services. Services as well as UoW are injected into controller (presenter, service facade or whatever) but in the same time UoW (or ObjectContext) must be injected into services so that internally used repositories can work with it. For this you need correct IoC lifetime manager so that it returns same instance for all injections within same "request". In case of web application you need PerHttpRequest lifetime manager (which you must implement by yourselves because Unity does not provide it).
One way is to manage this is to use the method described in http://mfelicio.wordpress.com/2010/02/07/managing-the-entity-framework-objectcontext-instance-lifetime-in-wcf-and-sharing-it-among-repositories/ That article implements the ContextManager for Wcf services. For ASP.NET app we could use something like this.
public class AspNetDBContextManager<TContext> : IDBContextManager
where TContext : IDBContext, new()
{
#region IDBContextManager Members
public IDBContext GetDBContext()
{
return this.GetOrCreateDbContext();
}
private IDBContext GetOrCreateDbContext()
{
if (HttpContext.Current == null)
{
throw new InvalidOperationException("Can be used only within ASP.NET applications");
}
string dbContextKey = string.Format("__AspNetDBCM__{0}__", HttpContext.Current.GetHashCode());
object dbContext = HttpContext.Current.Items[dbContextKey];
if (dbContext == null)
{
dbContext = new TContext();
if (dbContext != null)
{
HttpContext.Current.Items[dbContextKey] = dbContext;
}
}
return dbContext as IDBContext;
}
#endregion
}
public interface IDBContext
{
object Context { get; }
}
public interface IDBContextManager
{
IDBContext GetDBContext();
}

StructureMap injected IContainer - where does it come from?

I have an ASP.Net MVC application and I am using StructureMap within MVC to glue the whole application together. There are some model classes that have heavyweight dependencies that are not used in all public methods, so I pass in an IContainer to the model constructor and use that to create the heavyweight dependencies on demand.
My question is where does the IContainer come from that is injected? Is it a reference to the one held centrally by MVC (it's logical parent) or is it a brand new one created and configured solely for this class?
The container injected into a constructor that has an IContainer parameter is the same container that is creating the instance of the class with the constructor.
Jeremy Miller has expressed this behaviour as "IContainer is injected into itself by default" in his blog post on NHibernate with StructureMap.
Couldn't you go with a factory model for creating those dependencies when needed in order to reduce your coupling to the container?
You could make your model take a Func as parameter and use SM's ability to autoinject those:
public class MyModel
{
Func<IHeavyDep> _heavyFactory;
public MyModel(Func<IHeavyDep> dependency)
{
_heavyFactory = dependency;
}
public void UsesHeavy()
{
var heavy = _heavyFactory();
heavy.DoMyStuff();
}
}

Unit Testing with Nunit, Ninject, MVC2 and the ADO.Net Entity Data Model

I'm trying to get my head around using Nunit, Ninject, MVC2 and the ADO.Net Entity Data Model.
Let's say I have have a ProductsController instantiating a SqlProductsRepository class.
public class ProductsRepository : IProductsRepository
{
public MyDbEntities _context;
public ProductsRepository()
{
_context = new MyDbEntities();
}
public IList<Product> GetAllProducts()
{
return (from p in _context.Products select p).ToList();
}
}
public class ProductsController : Controller
{
public ActionResult ProductsList()
{
ProductsRepository r = new ProductsRepository();
var products = r.GetAllProducts();
return View(products);
}
}
I'd like to be able to perform unit testing on ProductsRepository to ensure this is returning the correct data but i'm not sure how to write the Test Class.
Every tutorial/document I've read so far points me to creating a Mock object using IProductsRepository and then injecting and testing the Controller.
This seems, to me, to bypass the concrete implementation.
MyDbEntities comes from an ADO.Net Entity Data Model .edmx
You're exactly right- mocking the repository does bypass the concrete implementation. That's the point.
Unit testing is not the same thing as functional testing. Your mock object can be set up to return whatever you explicitly define, then you test to ensure that constant inputs from your mock lead to expected results.
It sounds like you're wanting to create an integration test for ProductsRepository rather than a unit test, since you'd be testing against the database so that you can check it's giving you the right data.
It's when unit testing the Controller that you'd want to mock the ProductsRepository.
In my integration tests for ProductsRepository, I'd be doing the obvious things like
public void TestProductsRepository()
{
var context = new MyDbEntities();
// add a new product
var products = context.GetAllProducts();
// check products contains new product
}
With your two classes (ProductsRepository, ProductsController), you should have two sets of tests. One set of tests for each class.
When (unit) testing the ProductsController, you should mock its dependencies (in this case, the IProductsRepository). Bypassing the concrete implementations of the dependencies is the point.
There will be a completely different set of (integration) tests to validate that the ProductsRepository can hit the database and return correct data. In these integration tests you won't mock anything, since what you're testing is the interaction between a real repository with the actual database.