MVC Unit Testing with Unity Container - c#

I just have a quick question. Im trying to use Unity with my asp.net MVC project. Im coming across a problem when using the Unit of Work pattern with an EF context.
Say i inject the uow in the constructor, but have 4 or 5 actions in the controller that need to use the UnitOfWork in a using statement. This isnt going to work! Because Id have to do a
new UnitOfWork() in each action method.
should i be injecting a UnitOfWork into each action method? or into just the constructor? or should I even be injecting this at all!! The problem im facing is that i want to be able to unit test my controller with Mock data, and i can only do this if I inject the UnitOfWork or the DBContext.

Inject factory instead. This way you still achieve separation of concerns and loose coupling, yet you won't face any issues with using statements:
private IUnitOfWorkFactory factory;
public MyController(IUnitOfWorkFactory factory)
{
this.factory = factory;
}
public ActionResult MyAction()
{
using (var uow = factory.CreateUnitOfWork())
{
// ...
}
}
Edit:
Natural advantage of such approach is its configurability - you can register whichever factory you like to serve different controllers and wire it up at composition root:
// Note: this isn't unity syntax, but I hope my point is clear
container.Register<ISessionFactory, ReusableSessionFactory>("Reusable");
container.Register<ISessionFactory, FreshSessionFactory>("Fresh");
container.Register<IController, LoginController>().With("Fresh");
container.Register<IController, HomeController>().With("Reusable");
Now,
LoginController will use factory that under the hood serves new session upon each request
HomeController on the other hand will reuse the same session for all its lifespan
It's worth noting that from the controller point of view, it's irrelevant which factory serves the session as it's a mere implementation detail. That's why we hide session factory dependency behind abstraction (interface in this example) and perform all the object-to-dependency binding at application's root.

If I understand correctly you simply want to be able to test the UOW with something like Moq?
In that case for good design principles and proper separation of concerns you should create a base context for your database that each repository class uses.
Then you should create a repository interface for each domain model entity. Then you can implement the interface in a seperate repository library (this way you can implement a POCO model)
Finally you either create a service layer between your domain objects and your action methods or just use the required repository interfaces within the action methods.
I answer it like this because it depends on your application infrastructure. If you have no service layer then the best practice is to do the following:
public class AccountController : Controller
{
private readonly IAccountRepository _accountrepository;
public AccountController(IAccountRepository repository)
{
_accountrepository = repository;
}
}
I hope this helps.

Related

ASP.NET Core and ViewModelFactory

Hello, I'm trying to implement a ViewModelFactory "pattern" and I was wondering what's the best way to achieve it, considering the constraints of the current IoC container.
public class UserCreateViewModelFactory
{
private readonly DbContext db;
public UserCreateViewModelFactory(DbContext db){ this.db = db;}
public void Create(CreateUserViewModel viewModel)
{
//Creates the user
}
}
I have the above class easily injected into my controllers ctor. The head ache will come when I need more ViewModelBuilders, So I want to avoid two things:
Bloat ctor with injections
Bloat container with registrations
I want to be able to inject an IViewModelFactory on my controller and then using it like this:
[HttpGet]
public IActionResult GetUsers(int id)
{
return View(viewModelFactory.Build<GetUserViewModel>(id));
}
Notice that on calling Build(T) it has to call the correct IViewModelFactory implementation.
I know that StructureMap container support binding the concrete implementations to the corresponding interface but I'm trying to come up with a solution without having to add another dependecy to the project.
I think if you have builders for building viewmodels, then factory is extra layer of abstraction which simply can be dropped off.
Because you know the type of created viewmodel at compile time you can just inject a builder you need to the controller constructor.
If your controller create a lot of viewmodels and you end up with a lot of builders you need to inject - this can be considered as a sign of violation of Single Responsibility Principle. In that case you need to separate logic of controller to different controllers.
So I want to avoid two things:
Bloat ctor with injections
Separate class with bloated constructor to another classes with more specific responsibility which takes smaller amount of dependencies.
Or wrap dependencies with one or two, three classes based on their relation
Bloat container with registrations
This cannot be a problem, because dependency containers is usually designed to register whole "object graph" of your application
After sometime researching, I finally came up with a good solution for the this problem.
The solution is basically extending the default IoC capabilities through an IServiceCollection.ConnectImplementations() extension method.
During registration I'll search my concrete classes and connect them with its respective interfaces (like other containers). Then I use a Mediator/Proxy that has IServiceCollection injected and knows which concrete class should be building the view model.
The full solution is better explained by this gist I've created.

Best approach to pass database context from controller to model

I have read a lot of about IoC and design patterns but I´m not able to find clear answer. I´m doing whole data management in model, so I´m also creating database context in the model, but I found a solution from Benjamin Gale - When should I create a new DbContext(), which I like and it solves me a loft of problems with sharing db context, but my question is, how to pass this context from controller to model?
When I have ActionResult like this:
[Authorize, HttpPost]
public ActionResult AccountEditation(AccountEditationModel accountEditation)
{ ... }
Would be good solution to apply setter injection in AccountEditation actionResult, thats mean in each of actionResult method:
[Authorize, HttpPost]
public ActionResult AccountEditation(AccountEditationModel accountEditation)
{
accountEditation.db = Database; //Database from BaseController
...
}
Or is there any other way to do that?
Despite the name, ASP.NET MVC only loosely follows the MVC pattern. Namely, there's no true Model. Instead, your Model will be a combination of your entity, view models that represent that entity and your DAL, but each of these should be a separate thing. It's totally inappropriate to create or even inject a context into an entity class.
Your DAL will be the sole owner of the context. You should have an interface that represents an API that your application can use. Then, you should have one or more implementations of that interface, one per each discreet data access method (Entity Framework, Web Api, etc.). You'll then inject your context into this implementation and inject the implementation into your controller(s). The controllers, themselves, should only ever reference the interface. This is what's called the provider pattern, and it allows you sub-in different access methods as needed. Decided that you'd rather use Dapper than Entity Framework? Just create a new implementation for Dapper and inject that instead; none of the rest of your code needs to change.
The easiest thing I have found is to inject a repository into the Controller via Unity. And then pass the repository, if you need to, to whatever service or class you're using to process your business logic.
Basically...
public class AccountController : Controller
{
private IRepository<Account> _accountRepository;
public AccountController(IRepository<Account> accountRepository)
{
this._accountRepository = accountRepository;
}
}
When you use Unity and set it up properly, you can automatically inject whatever repository you're using into the AccountController class. After that, you shouldn't have a problem passing that same repository to other services or classes that need it.
Unity Dependency Injection

How to use Simple injector for repository in business layer

I would like that in my MVC layer there will be no Repositories at all.
I've generic EFRepository, IRepository and PASContext (which inherits from DbContext) in my DAL project layer .
I've installed Simple Injector with quick start under my MVC project and thats allows me to get in the constructor of each controller the repository i want .
But in my solution i have also BLL project and i want MVC layer to talk only with the BLL layer, as this is the project architecture and in the future i would like to add logic in the classes within the BLL layer .
Also i don't want to create a context in my BLL layer, but the Repository has no constructor which takes 0 arguments, this is my ProductBLL class :
public class BLLProducts
{
IRepository<Product> ProductRepository;
public BLLProducts(EFRepository<Product> Repository)
{
ProductRepository = Repository;
}
public ICollection<Product> getAll()
{
return ProductRepository.All().ToList();
}
}
How can i initiate the BLLProduct class from a controller or from a unitTest without creating a repository/context ? so i can keep my abstraction here.
I know i need to use somehow the Simple injector here, i just dont know how .
From perspective of the controller, it's just a matter of injecting the BLLProducts into it, like this:
// constructor
public HomeController(BLLProducts products) {
this.products = products;
}
From a unit testing perspective, letting the controllers depend on concrete classes is suboptimal (it violates the Dependency Inversion Principle). This is sub optimal, since you now need to create a BLLProducts instance and instantiate it with a DbContext, but this DbContext is specific to Entity Framework, which depends on a database. This makes testing harder and slower. You want your unit tests to run without a database.
So the solution to this is to hide this BLLProducts class behind an abstraction. A simple way to do this is extract an interface out of this class:
public interface IBLLProducts {
ICollection<Product> getAll();
}
This makes unit testing the controllers much easier. The only thing you have to do is let it depend on this new interface:
public HomeController(IBLLProducts products) {
this.products = products;
}
You will need to register this IBLLProducts interface in Simple Injector:
container.Register<IBBLProducts, BLLProducts>();
This whole model still has some downsides to it. For instance, although Simple Injector can create and dispose a DbContext for you, where do you call SubmitChanges? Doing this when the web requests ends is a pretty bad idea. The only convenient solution I found for this is to move to a more SOLID architecture. For instance, take a look at this question.

N-Tier Architecture with Service Layer, Business Layer, and Entity Framework

Just wanted some feedback/help with the way I'm architecturing my application. My current solution structure looks something like this:
UI (Actual MVC application)
Core (only Controllers & ViewModels)
Services
BLL
Data (Entity framework DbContext, mapped to Domain objects)
Domain (Simple POCO objects)
Interfaces
Other stuff
Ninject to inject DbContext into Controller (per request)
AutoMapper to map Domain objects to ViewModel
All assemblies have a reference to the Interfaces project, which, as the name suggests, is nothing more than simple interfaces (i.e. IDbContext, IRepository, etc).
The Services project "ties" together everything else. It is the only assembly which has a direct reference to the Data access layer (Entity Framework).
I've provided some code below:
An example of a Controller looks like this:
namespace Core.Controllers
{
public class HomeController : Controller
{
private IDbContext dbContext;
public HomeController(IDbContext dbContext)
{
this.dbContext = dbContext;
}
public ActionResult Users()
{
UserService userService = new UserService(dbContext);
var users = userService.GetAllUsers();
return View(Mapper.Map<IEnumerable<UserListViewModel>>(users));
}
...
The UserService class:
namespace Services
{
public class UserService
{
private readonly IDbContext dbContext;
public UserService(IDbContext dbContext)
{
this.dbContext = dbContext;
}
public IEnumerable<User> GetAllUsers()
{
IRepository<User> userRepository = new Repository<User>(dbContext);
UserBLL userBLL = new UserBLL(userRepository);
return userBLL.GetAllUsers();
}
...
Finally, the business layer class:
namespace BLL
{
public class UserBLL
{
private readonly IRepository<User> userRepository;
public UserBLL(IRepository<User> userRepository)
{
this.userRepository = userRepository;
}
public IEnumerable<User> GetAllUsers()
{
return userRepository.Get();
}
...
I'm looking for some feedback/ways to improve. I notice that for basic tasks, my service layer methods will be exactly the same as the business layer methods (i.e. "pass through" functions). What I'm hoping is that this abstraction will be helpful for more complex tasks which may require calls to multiple business layer methods. Would it just be better to include business logic in the service layer?
From a quick glance, I don't think your service and controller/core layer should have the db context injected into them in this manner. They don't actually directly depend on it and doing it in this manner causes some coupling that is not ideal. The core layer should have the user service injected and the user service and BLL should have the repository injected. The repository should have the dbcontext injected by your DI framework and not passed in as a dependency.
Why are you using dependency injection when you are creating dependencies directly in the service?
public IEnumerable<User> GetAllUsers()
{
IRepository<User> userRepository = new Repository<User>(dbContext);
UserBLL userBLL = new UserBLL(userRepository);
return userBLL.GetAllUsers();
}
Btw. why are you using so many layers when they actually do nothing? Your example code just shows that using context in controller directly would produce the same result without three wrapper useless layers. It may be just problem of your example but each layer should bring some added logic. If you just use it to call something on lower layer you are most probably overarchitecting your code. This is called onion architecture. That is also a reason why it is not a bad practice to add layer once you need it - not upfront.
Please check this out: http://www.primaryobjects.com/CMS/Article122.aspx EF Repository pattern + Unit Of Work pattern. As for your other layers, it really depends on the application and what it needs to accomplish. Please provide more details on what you're trying to do.
Some of the improvements in organizing projects and design of the layers can be done by focusing on getting the Domain objects correct.
You said you have simple POCO objects as Domain, but the Domain objects should be the one having all the "State and behaviour" of the business. That means you do not need to have BLL and Domain assemblies separate.
Once the Domain objects are defined, EF can be used to create the context and entity classes (which are not Domain classes unless there is no additional behaviour compared to your domain object, but still having them different might be good for future requirements).
Other minor point is, I think having interfaces distributed within the Domain and Services layer is better in terms of anyone understanding each layer in isolation.

I know how to use dependency injection but I recognize no practical advantage for it

It is about this (Inject the dependency)
private readonly ICustomerService _customerService;
public Billing(ICustomerService customerService)
{
_customerService = customerService;
}
versus this (Create the dependency)
private readonly ICustomerService _customerService;
public Billing()
{
_customerService = new CustomerService();
}
The latter sample so they say is bad because... it violates DI...of course nothing is injected... but what if DI would not exist, what is so bad that the CustomerService is created manually from the Billing class? I see no practical advantage concerning exchangeability of the Service interface.
I ask for a practical example with source code may it be a unit test or showing a practical solution why it is so much more loose coupling.
Anyone keen enough to show his DI muscles and why it has a practical right to exist and be applied?
UPDATE
So people have not to read all up I will write here my short experience:
DI as a pattern has a practical usage. To follow DI by not injecting all services manually (a poor mans DI tool so they say...) use a DI framework like LightCore/Unity but be sure you use the right tool for the appropriate job. This is what I did not;-) Developing a mvvm/wpf application I have other requirements the LightCore/Unity tool could not support they even were a barrier. My solutions was to use MEFEDMVVM with which I am happy. Now my services are automatically injected at runtime not at startup time.:-)
Understanding the how and understanding the why are very different things..
One of the biggest benefits of DI is for unit testing. In your second example it's impossible to unit test Billing without also testing CustomerService (and also testing any further dependencies in the chain). In that case you're not unit testing, you're integration testing! If you want a good rationale for using DI, you need not look any further than a rationale for unit testing..
Imagine that CustomerService connects to your CRM system and your database. It creates a whole bunch of network connections to retrieve data about the customer and maybe reads additional things from the database to augment that before returning the data to the Billing class to use in its calculation.
Now you want to unit test Billing to make sure the calculations it's making are correct (you don't want to send out wrong bills right?)
How will you unit test Billing if its constructor is tied to a class that requires connections to a real CRM system and database? Wouldn't it be better to inject that dependency as an interface, easily allowing you to provide a mock version for your tests?
That is why DI is useful.
DI Comes in useful, when you want to pass different implementations of the Interface to your class, for example: Unit Testing.
Say your Billing constructor is an MVC controller's constructor, and your CustomerService took some form of IDataContext as a parameter.
Global.asax
// Does the binding
ICustomerService binds to CustomerService
IDataContext binds to EntityFrameworkContext
CustomerService
private IDataContext _datacontext;
public CustomerService(IDataContext dataContext)
{
_dataContext = dataContext;
}
public AddCustomer(Customer entity)
{
this._dataContext.Customers.Add(entity);
this._dataContext.SaveChanges;
}
MVC Controller
private ICustomerService _customerService;
public Billing(ICustomerService customerService)
{
_customerService = customerService;
}
public ActionResult NewCustomer()
{
Customer customer = new Customer(){ Name = "test" };
this._customerService.AddCustomer(customer);
return View();
}
Say you wanted to unit test your Services, or Controllers. You would pass in the CustomerServices, but you would pass in a fake implementation of the EntityFrameWorkContext.
So a FakeDbContext, that implements IDataContext, is passed to customer services.
The FakeDbContext may just store the entities in Lists or a more elaborate storage mechanism, the point being, you can inject different implementations of dependencies, which allows you to alter the behaviour of one component without having to modify your code elsewhere.
In my experience it is not only about avoiding integration test (but that is a very important point too). Instantiating classes on the inside can create a lot of work unit testing. A class like CustomerService might depend on an open Database connection, configuration files, services being available and a lot of other stuff, that you should not have to know about, when your job is to test the Billing class only.
That being said, sometimes it is a pain always to inject everything. Injection frameworks might lighten that load, but I'm not at big fan. Another kind stackoverflow user pointed me to what he called "poor mans injection". Basically it consists of two constructor overloads: One constructor with the injected interface, and one without. The one without does nothing but instantiate a concrete class that implements the interface, and pass it to the other constructor. It goes something like this:
public class Billing
{
ICustomerService _customerService;
public Billing():this(new CustomerService()) {}
public Billing(ICustomerService customerService)
{
_customerService = customerService;
}
}
This way you have an way to inject when testing AND a way to construct the class with a default implementation of the interface. Not everybody loves this pattern, but I find it practical for some scenarios.

Categories