Managing Constructor Dependency Injection (MS Unity) - asp.net-mvc

I am building a multi-layered application and trying to keep the layers as much as possible so I'm using an IoC container for this purpose. Anyway, I'm trying to expand on this article to move my business logic validation into the service layer. I managed to resolve all dependency issues except the dependency of the ModelStateWrapper class on the ModelState itself. Here are my classes:
public interface IValidationDictionary
{
void AddError(string key, string errorMessage);
bool IsValid { get; }
}
public class ModelStateWrapper : IValidationDictionary
{
private ModelStateDictionary _modelState;
public ModelStateWrapper(ModelStateDictionary modelState)
{
_modelState = modelState;
}
public void AddError(string key, string errorMessage)
{
_modelState.AddModelError(key, errorMessage);
}
public bool IsValid
{
get { return _modelState.IsValid; }
}
}
The ModelStateWrapper class resides in a Services folder in my MVC3 application. While the IValidationDictionary is inside an Abstract folder inside my Services layer. In my Unity configuration I did the following:
.RegisterType<IValidationDictionary, ModelStateWrapper>(
new HttpContextLifetimeManager<IValidationDictionary>())
So, now is there anything I could do to inject the ModelState object into the ModelStateWrapper class using the IoC? Or do I have to explicitly/manually instantiate the ModelStateWrapper in the controllers and pass in the ModelState as an argument?
Thanks in advance!

I think you need to move your modelstatewrapper class to a common assembly. You can reference this common assembly from your service layer, business logic layer, etc. The common assembly can contain your domain classes, dto's, service definitions, etc etc You create a bootstrapper class which registers all types from the common assembly into your container. Call this bootstrapper from the service, BL layer, etc.
I hope this helps
Greetings

Related

Dependency injection with multiple-layered application

I'm currently struggling a bit to understand how I can use the dependency injection pattern outside of my controller classes.
Say for instance that I have the following controller:
public class TestController : Controller {
ILog logger;
public TestController(ILog log) {
logger = log;
}
public string TestMethod() {
businessLayer businessLayer = new businessLayer();
return businessLayer.DoSomethingAndLogIt();
}
}
I understand that in most cases it is not possible to use constructor injection outside of the controller-classes. So it would not be possible to directly use the ILog-implementation insdie the "businesslayer"-class.
One simple solution I could imagine is the following:
public class TestController : Controller {
ILog logger;
public TestController(ILog log) {
logger = log;
}
public string TestMethod() {
businessLayer businessLayer = new businessLayer(logger);
return businessLayer.DoSomethingAndLogIt();
}
}
So passing on the dependencies from the controller to the underlaying layers. But is this the best way? Are there better solutions to have my businessLayer-class access to the ILog-implementation?
Thx!
I understand that in most cases it is not possible to use constructor
injection outside of the controller-classes.
This is incorrect. You should use constructor injection for all your components (every class in your application that contains behavior).
Dependency injection is about injecting dependent services/components into consuming components. So this means that you should not new up the businesslayer class in your controler; you should inject it using the constructor. By newing up this dependency you are violating the Dependency Inversion Principle, which causes high coupling. This again makes your code harder to test and makes it harder to change the controller and makes it much harder to apply cross-cutting concerns (such as logging, audit trailing, transaction management, etc) to the system.
So it would not be possible to directly use the ILog-implementation
insdie the "businesslayer"-class.
Incorrect. The ILog implementation should be injected into the constructor of your businesslayer class.
Long story short, your controller should look like this:
public class TestController : Controller {
IBusinessLayer businessLayer;
public TestController(IBusinessLayer bl) {
this.businessLayer = bl;
}
public string TestMethod() {
return businessLayer.DoSomethingAndLogIt();
}
}
Since TestController doesn't seem to use ILog directly, it should not be injected into its constructor. ILog is an implementation detail of the business layer class and implementation details should not leak to the consumer (this would again be a violation of the Dependency Inversion Principle).

How can I inject the Repositories to the UnitOfWork?

I've implemented my UnitOfWork so that it keeps references to all repositories.
public interface IUnitOfWork
{
void Commit();
void RollBack();
}
public interface IMyUnitOfWork : IUnitOfWork
{
IFooRepository Foos { get; }
IBarRepository Bars { get; }
// Other repositories ...
}
Note that the repositories implements a generic type of repository interface.
public interface IFooRepository : IRepository<Entities.Foo>
{
// FooRepository specific methods goes here.
}
public interface IRepository<T> : IRepository
where T : class
{
}
Now how can I inject these repository to my UnitOfWork. Of course I want them with a lazy loading behavior. For example:
public class ConcreteUnitOfWork : IMyUnitOfWork
{
private readonly IUnityContainer unityContainer;
private IFooRepository fooRepository;
public ConcreteUnitOfWork(IUnityContainer unityContainer)
{
this.repositoryFactory = repositoryFactory;
}
public IFooRepository Foos
{
get
{
return this.fooRepository ??
(this.fooRepository = unityContainer.Resolve<IFooRepository>());
}
}
}
I know passing the Unity container to the UnitOfWork is incorrect but what pattern would you offer to solve this issue?
You may mention that I shouldn't keep the repository references in the UnitOfWork but please suppose a service class which needs several repositories. With this design I can just pass the UnitOfWork as the constructor parameter (Constructor Injection) to the service class, but if I didn't keep the repository references in UnitOfWork, I would have to pass all needed repositories as constructor parameters and you know what it leads to.
-- UPDATE --
Please let me know if I'm absolutely wrong and I should never compose the repositories in UnitOfWork. Then please give me a solution about "Constructor Over-injection" here.
-- UPDATE2 --
It seems that composing (referencing to) the repositories from UnitOfWork breaks the Open/Closed principle as we need to change the UnitOfWork class when we add a new repository (add a new property).
If it's right then I should consider a refactoring. Would you please give me some ideas?
It seems as though the current design proposal mixes more than one responsibility into the IMyUnitOfWork interface. You say that this is because otherwise a service class might need to take each Repository independently. I'm assuming you mean something like this:
public MyService(
IUnitOfWork uow,
IFooRepository fooRepository,
IBarRepository barRepository)
This seems to me to be a much simpler and cleaner design.
But then what about Constructor Over-injection?
Well, there's that... but the thing is that this is exactly the same problem you now have with your ConcreteUnitOfWork implementation. You haven't solved the Constructor Over-injection smell at all - you've just moved it to another class.
Actually, by moving it to ConcreteUnitOfWork you've made it more difficult to deal with the situation. Because ConcreteUnitOfWork is a pure infrastructure class (or a support class, if you will) it doesn't have any business context, so it's really hard to suggest a way resolve the Constructor Over-injection smell here.
On the other hand, a given Service (or perhaps a Controller) would tend to be more specialized and have knowledge of the business context, so it wouldn't need every repository in order to do its job - or if it does, it probably attempts to do too much.
Such a specific business component can better be refactored to a Facade Service.

NInject and MVC 3 - Should I use DependencyResolver instead of [Inject] attribute?

Recently I moved to MVC 3 and Ninject 2. In most of the code, I use constructor injection, but there are some places, where I had to use Inject attribute. Ninject 2 registers its own IDepencyResolver interface. I don't like DependencyResolver class being part of System.Web.Mvc namespace, because its function is not really strictly related to MVC, but now, when it is there, I can do
public SomeClass
{
public IUserService UserService { get; set; }
public SomeClass()
{
UserService = DependencyResolver.Current.GetService<IUserService>();
instead of
public SomeClass
{
[Inject]
public IUserService UserService { get; set; }
so I don't have to reference Ninject namespace in my classes. Should DependencyResolver be used like that?
I use property injection only for dependencies that are not required for the proper working of the class but could add some functionality if the user sets them. Example of such functionality is logging. So you could have a property which represents a logger where the user can supply his own implementation and if he doesn't the class continues to work normally but it simply doesn't log.
For everything else I use constructor injection. This way you indicate to the consumer that this class has a required dependency on some other service.
So to answer your question about the property injection I would simply have:
public SomeClass
{
public IUserService UserService { get; set; }
public void SomeMethodWhichDoesntEnforceUserService()
{
if (UserService != null)
{
// Provide some additional functionality
}
}
}
and if your class cannot function properly without the user service:
public SomeClass
{
private readonly IUserService _userService;
public SomeClass(IUserService userService)
{
_userService = userService;
}
public void SomeMethodWhichRequiresTheService()
{
_userService.DoSomething();
}
}
So in both cases no reference to any DI specifics. That's what Inversion of Control is all about.
First question I would ask is why you can not perform constructor injection of the IUserService into SomeClass? It may indicate an issue with the design.
To avoid direct reference to the DependencyResolver you could implement some form of abstraction of a Service Locator over the DI framework, e.g. CommonServiceLocator, but as the answer to this question indicates, such abstractions shouldn't be necessary when doing DI correctly. Instead you should adjust the design of the application.
I believe the ninject.web.mvc version for mvc3 now supports constructor injection on filter attributes. Have you tried it?

Where does my CRUD LINQ Code Go? ASP.NET MVC

I am currently using the ASP.NET MVC framework on a project (pretty much my first time)
I am using Linq2SQL as my data model..
Where should i have this kind of code:
var entries = from e in db.sometable select e;
I currently have this kinda code in the controller and pass the data i get into the view..
is this ok?
if not how do i entend my linq2sql datamodel to include this kindof code?
Thanks
Daniel
To add what #Poco said, here's an example:
In Foo.Common.Repositories (inside the Foo.Common Project):
public interface IRepository<T>
{
IEnumerable<T> GetAll();
void Update(T entity);
void Add(T entity);
void Delete(T entity);
void Save();
}
public interface IUserRepository : IRepository<User>
{
void GetByCredentials(string username, string password);
}
The inside Foo.Data.Repositories (inside Foo.Data project):
public class UserRepository
{
// ... other methods/properties snipped.
public IEnumerable<User> GetAll()
{
// Where this.Users would be L2Sql or Code-First... or some other ORM.
return from u in this.Users orderby u.Name select u;
}
}
Then inside your actual Foo.Web:
public class UserController : Controller
{
private readonly IUserRepository userRepository;
public UserController(IUserRepository userRepository)
{
this.userRepository = userRepository;
}
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult List()
{
var users = this.userRepository.GetAll();
return this.View(users);
}
}
And inside your Global.asax you'd have Ninject or some other IoC container to resolve IUserRepository:
public static void RegisterServices(IKernel kernel)
{
kernel.Bind<IUserRepository>().To<UserRepository>();
}
protected void Application_Start()
{
var kernel = new StandardKernel();
AreaRegistration.RegisterAllAreas();
MvcApplication.RegisterGlobalFilters(GlobalFilters.Filters);
MvcApplication.RegisterRoutes(RouteTable.Routes);
MvcApplication.RegisterServices(kernel);
// I'm using MVC3 here:
DependencyResolver.SetResolver(new NinjectResolver(kernel));
}
It's common to use the Repository pattern for MVC.
Typically, you define an interface, for instance, IProducts, and then, you implement this interface, calling you linq2sql code. Your controller will accept this interface as a parameter for the constructor, so that it depends on this interface, and not on a concrete class. Using a dependency injector, such as Ninject, will allow you to supply a concrete interface implementation to the constructor. This enables Unit Testing on you web app, and also adds flexibility.
There's a really nice book, Pro ASP.NET MVC 2 Framework, that explains all that. I'm currently reading it, and I just love it.
Here's an example of how to implement the repository pattern
In addition to this I would implement an additional layer to handle your applications business logic and keep your controllers lightweight
It's fine to have Linq queries in controller methods.
If we're talking about separation of concerns, the idea is that your data layer (in this case, the repository(?) code that supplies you with db.sometable) decouples your logic code (controller methods in this case) from the datastore.
You query the data layer rather than the database, so you can change the underlying datastore and your controller code will still work.
Some would argue that it's better again to move as much logic code as you can out of the controllers and into your model code (see the first answer here), but it depends how far you want to go.

Why are there 2 constructors in the Default AccountController provided by the MVC?

here's the default AccountController.cs that's generated by the framework.
public class AccountController : Controller
{
public IFormsAuthentication FormsAuth { get; private set; }
public IMembershipService MembershipService { get; private set; }
public AccountController()
: this(null, null)
{
}
public AccountController(IFormsAuthentication formsAuth, IMembershipService membershipService)
{
FormsAuth = formsAuth ?? new FormsAuthenticationService();
MembershipService = membershipService ?? new AccountMembershipService();
//---
}
This is easy to understand.
public AccountController(IFormsAuthentication formsAuth,
IMembershipService membershipService)
{
FormsAuth = formsAuth ?? new FormsAuthenticationService();
MembershipService = membershipService ?? new AccountMembershipService();
}
What's this? What's its purpose? Is it particular to the Account Controller or is it a requirement for other controllers? and, why should I incorporate it in my project?
public AccountController()
: this(null, null)
{
}
They seem to use this type of constructors in two other places.
Thanks for helping
This is actually an implemenation of the Bastard Injection anti-pattern.
The idea is that Constructor Injection is supported to allow Dependency Injection (DI), while still providing a default constructor for default behavior.
It's really not necessary to have the default constructor, but if you omit it, you must supply a custom IControllerFactory, as the DefaultControllerFactory assumes that all Controllers have default constructors.
ASP.NET MVC is built with DI in mind, but I guess that to keep it simple, the Bastard Injection pattern was used for the project template to avoid forcing a specific IControllerFactory upon developers.
If you use a DI framework (like Unity) and you active your controllers via the container, it might not find the dependencies and use the default constructor (in this case).
If you would like use use generics, something like ... where T : IController, new() you will need a default constructor.
Another reason for having a default (no parameter) constructor is for Reflection.
The classes in the System.Reflection namespace, together with Type, allow you to obtain information about loaded assemblies and the types defined within them, such as classes, interfaces, and value types. You can also use reflection to create type instances at run time, and to invoke and access them.
There might be times where you need to create a temporary object of that type in order to reflect over it's properties or methods, but don't want or need the overhead of creating a real object - especially if that entails accessing a database or remote service for example.

Resources