Where should I create the Unit of Work instance in an ASP.Net MVC 3 application? - asp.net-mvc-3

I have read as many of the posts on Stackoverflow as I can find with regards the use of a Unit of Work pattern within
an ASP.Net MVC 3 application which includes a Business Layer. However, I still have a couple of questions with
regards this topic and would greatly appreciate any feedback people can give me.
I am developing an ASP.Net MVC 3 Web application which uses EF 4.1. I will be using both the Repository and
Unit of Work Patterns with this project similar to how they are used in this great tutorial
The difference in my project is that I need to also include a Business Layer (separate project in my solution) in order to
carry out the various business rules for the application. The tutorial mentioned above does not have a Business layer, and
therefore creates an instance of the Unit of Work class from the controller
public class CourseController : Controller
{
private UnitOfWork unitOfWork = new UnitOfWork();
However, my question is, where should I create the instance of the Unit of Work class if I have a Business Layer?
I personally think it should be created in my controller and then injected into the Business Layer like so:
public class PeopleController : Controller
{
private readonly IUnitOfWork _UoW;
private IPersonService _personService;
public PeopleController()
{
_UoW = new UnitOfWork();
_personService = new PersonService(_UoW);
}
public PeopleController(IUnitOfWork UoW, IPersonService personService)
{
_UoW = UoW;
_personService = personService;
}
public ActionResult Edit(int id)
{
Person person = _personService.Edit(id);
return View(person);
}
public class UnitOfWork : IUnitOfWork, IDisposable
{
private BlogEntities _context = new BlogEntities();
private PersonRepository personRepository = null;
public IPersonRepository PersonRepository
{
get
{
if (this.personRepository == null)
{
this.personRepository = new PersonRepository(_context);
}
return personRepository;
}
}
public void Save()
{
_context.SaveChanges();
}
public class PersonService : IPersonService
{
private readonly IUnitOfWork _UoW;
public PersonService(IUnitOfWork UoW)
{
_UoW = UoW;
}
public Person Edit(int id)
{
Person person = _UoW.PersonRepository.GetPersonByID(id);
return person;
}
public class PersonRepository : IPersonRepository
{
private readonly BlogEntities _context;
public PersonRepository(BlogEntities context)
{
_context = context;
}
public Person GetPersonByID(int ID)
{
return _context.People.Where(p => p.ID == ID).Single();
}
I have read others saying that the Unit of Work instantiation should not be in the Controller, but created in the Service Layer
instead. The reason why I am not so sure about this approach is because my Controller may have to use several different
Service Layers in one business transaction, and if the Unit of Work instance was created inside each Service, it would result in several
Unit of Work instances being created, which defeats the purpose, ie, one Unit of Work per business transaction.
Maybe what I have explained above is wrong, but if so, I would greatly appreciate if someone could put me right.
Thanks again for your help.

I think you have a couple of changes to make:.
Allow your DI container to inject a UnitOfWork instance into your Service classes in their constructors, and leave it out of your Controller altogether.
If your DI container supports it (Ninject does, for example), configure your UnitOfWork to be managed on a per-request basis; this way your services will be handed a distinct UnitOfWork for each request, and you're all done. Or...
If your DI container does not support per-request lifetimes, configure it to manage the UnitOfWork as a singleton, so every Service class gets the same instance. Then update your UnitOfWork to store its Entities object in a data store which stores objects on a per-request basis, for example in HttpContext.Current.Items, as described here.
Edit 1
Regarding where the UnitOfWork should be injected; I'd say the Service layer is the correct place. If you imagine your system as a series of layers where the outer layers deal with user interactions and the lower layers deal with data storage, each layer should become less concerned with users and more concerned with data storage. UnitOfWork is a concept from one of the 'lower-level' layers and Controller is from a higher-level layer; your Service layer fits between them. It therefore makes sense to put the UnitOfWork into the Service class rather than the Controller.
Edit 2
To elaborate on the UnitOfWork creation and it's relationship to HttpContext.Current.Items:
Your UnitOfWork would no longer hold a reference to an Entities object, that would be done through the HttpContext object, injected into the UnitOfWork behind an interface like this:
public interface IPerRequestDataStore : IDisposable
{
bool Contains(string key);
void Store<T>(string key, T value);
T Get<T>(string key);
}
The HttpContext object would then implement IPerRequestDataStore like this:
public class StaticHttpContextPerRequestDataStore : IPerRequestDataStore
{
public bool Contains(string key)
{
return HttpContext.Current.Items.Contains(key);
}
public void Store<T>(string key, T value)
{
HttpContext.Current.Items[key] = value;
}
public T Get<T>(string key)
{
if (!this.Contains(key))
{
return default(T);
}
return (T)HttpContext.Current.Items[key];
}
public void Dispose()
{
var disposables = HttpContext.Current.Items.Values.OfType<IDisposable>();
foreach (var disposable in disposables)
{
disposable.Dispose();
}
}
}
As an aside, I've called it StaticHttpContextPerRequestDataStore as it uses the static HttpContext.Current property; that's not ideal for unit testing (another topic altogether), but at least the name indicates the nature of its dependency.
Your UnitOfWork then passes the IPerRequestDataStore it's given to each of its Repository objects so they can access the Entities; this means that no matter how many UnitOfWork instances you create, you'll use the same Entities object throughout a request because it's stored and retrieved in the IPerRequestDataStore.
You'd have an abstract base Repository which would use its IPerRequestDataStore to lazy-load its Entities object like this:
public abstract class RepositoryBase : IDisposable
{
private readonly IPerRequestDataStore _dataStore;
private PersonRepository personRepository;
protected RepositoryBase(IPerRequestDataStore dataStore)
{
this._dataStore = dataStore;
}
protected BlogEntities Context
{
get
{
const string contextKey = "context";
if (!this._dataStore.Contains(contextKey))
{
this._dataStore.Store(contextKey, new BlogEntities());
}
return this._dataStore.Get<BlogEntities>(contextKey);
}
}
public void Dispose()
{
this._dataStore.Dispose();
}
}
Your PeopleRepository (for example) would look like this:
public class PeopleRepository : RepositoryBase, IPersonRepository
{
public PeopleRepository(IPerRequestDataStore dataStore)
: base(dataStore)
{
}
public Person FindById(int personId)
{
return this.Context.Persons.FirstOrDefault(p => p.PersonId == personId);
}
}
And finally, here's the creation of your PeopleController:
IPerRequestDataStore dataStore = new StaticHttpContextDataStore();
UnitOfWork unitOfWork = new UnitOfWork(dataStore);
PeopleService service = new PeopleService(unitOfWork);
PeopleController controller = new PeopleController(service);
One of the central concepts here is that objects have their dependencies injected into them via their constructors; this is generally accepted as good practice, and more easily allows you to compose objects from other objects.

Related

Wrapper class in MVC3

I want to create a wrapper class so that all queries should not be in controller. Currently select queries are placed in Controller. But I want to create another layer for abstraction.
I already created a viewmodel class. But wrapper class is something else.
How do I do that?
I don't do any queries directly in my controllers. I have a service layer which my controller would call, and each service layer would do a call to the repository to insert, update or delete data or bring back data.
The sample code below uses ASP.NET MVC3 and Entity Framework code first. Lets assume you want to bring back all the countries and use it for whatever reason in your controller/view:
My database context class:
public class DatabaseContext : DbContext
{
public DbSet<Country> Countries { get; set; }
}
My country repository class:
public class CountryRepository : ICountryRepository
{
DatabaseContext db = new DatabaseContext();
public IEnumerable<Country> GetAll()
{
return db.Countries;
}
}
My service layer that calls my repository:
public class CountryService : ICountryService
{
private readonly ICountryRepository countryRepository;
public CountryService(ICountryRepository countryRepository)
{
// Check for nulls on countryRepository
this.countryRepository = countryRepository;
}
public IEnumerable<Country> GetAll()
{
// Do whatever else needs to be done
return countryRepository.GetAll();
}
}
My controller that would call my service layer:
public class CountryController : Controller
{
private readonly ICountryService countryService;
public CountryController(ICountryService countryService)
{
// Check for nulls on countryService
this.countryService = countryService;
}
public ActionResult List()
{
// Get all the countries
IEnumerable<Country> countries = countryService.GetAll();
// Do whatever you need to do
return View();
}
}
There are lots of info on the internet on how to get you data and display it, inserting, editing, etc. A good place to start is at http://www.asp.net/mvc. Work through their tutorials, it will do you good. All the best.

How to Moq a service in a controller which use unitofwork with generic repository

I am a newbie in TDD (Asp.net MVC3 environment) and trying to adopt TDD as our better better development approach.
In our production code,we have a following scenario
In web
//Autofac used to resolve Dependency
TestController(XService xSerivice,YSerivice yService)
{_xService =xService,_YService= yService}
[HTTPPost]
ActionResult Create(A1 a1)
{
_xService.XUnitOfWork.A1.add(a1)
_xService.XUnitOfwork.SaveChanges();
}
// where X, Y are different context,Concrete class, no interface implemented!
In Business Layer
Xservice(XUnitofWork) // no interface implemented!
In DAL Layer
'XUnitofWork:DataRepostory(Generic)...
{
GenericRepository<a1Entity> A1,
GenericRepository<a2Entity> A2
}
Now I realize that we should implement interface both in our BAL and Web layer.
My question is are there any way i can mock the services(XService,YService) in our controller to test some behavior (TDD) [for example save change exception occur while saving a entity via' _xService.XUnitOfwork.SaveChanges()'?
Please help.Thanks in Advance!
If you mark members (properties, methods) in your concrete class as virtual, I think you may be able to just mock those methods / properties individually. (I think the VB equivalent of virtual is Overridable..?)
Moq works by creating a new concrete implementation of something at runtime when your test runs. This is why it works so well with interfaces and abstract classes. But if there is no interface or abstract class, it needs to override a method or property.
Reply to question author's answer:
Since you are a self-proclaimed TDD newbie, I just wanted to point out that adding a parameterless constructor to a class just for the sake of making the class testable should not be an acceptable solution.
By giving your GenericRepository class a hard dependency on Entity Framework's DbSet / IDbSet, you are creating a tight coupling between your repository implementation and EF... note the using System.Data.Entity line at the top of that file.
Any time you decide to add a constructor dependency, you should seriously consider adding it as an interface or abstract class. If you need access to members of a library which you do not control (like EF's DbContext), follow Morten's answer and wrap the functionality in your own custom interface.
In the case of DbContext, this class does more than just provide you with a UnitOfWork implementation. It also provides you a way of querying out data and adding / replacing / removing items in your repository:
public interface IUnitOfWork
{
int SaveChanges();
}
public interface IQuery
{
IQueryable<TEntity> GetQueryable<TEntity>() where TEntity : class;
}
public interface ICommand : IQuery
{
void Add(object entity);
void Replace(object entity);
void Remove(object entity);
}
You can pretty easily wrap DbContext in these 3 interfaces like so:
public class MyCustomDbContext : DbContext, IUnitOfWork, ICommand
{
// DbContext already implements int SaveChanges()
public IQueryable<TEntity> GetQueryable<TEntity>() where TEntity : class
{
return this.Set<TEntity>();
}
public void Add(object entity)
{
this.Entry(entity).State = EntityState.Added;
}
public void Replace(object entity)
{
this.Entry(entity).State = EntityState.Modified;
}
public void Remove(object entity)
{
this.Entry(entity).State = EntityState.Deleted;
}
}
Note how your interfaces take no dependencies on System.Data.Entity. They use primitives and standard .NET types like object, IQueryable<T>, and int. This way, when you give your generic repository dependencies on the interfaces, you can remove the dependency on System.Data.Entity:
// using System.Data.Entity; // no need for this dependency any more
public class GenericRepository
{
private readonly ICommand _entities;
private readonly IQueryable<TEntity> _queryable;
public GenericRepository(ICommand entities)
{
this._entities = entities;
this._queryable = entities.GetQueryable<TEntity>();
}
//public GenericRepository()
//{
// no need for a parameterless constructor!
//}
}
...and your GenericRepository is now fully unit testable, since you can easily mock any of these interface methods.
Final Notes:
Also, after seeing your answer to your own question, it looks like you have CompanyRepository as a property of your UnitOfWork class. You then inject UnitOfWork as a dependency on your CompanyInformationController. This is backwards. Instead, you should be injecting the CompanyRepository (or its interface) into the controller's constructor. The UnitOfWork pattern has nothing to do with maintaining references for your known repositories. It is about tracking multiple changes made to related items so that they can all be pushed once as a single transaction. EF does this automatically, so as long as AutoFac is providing the same DbContext instance no matter whether your app requests an IQuery, ICommand, or IUnitOfWork implementation, then the only method UnitOfWork should be concerned with is SaveChanges().
thanks for your reply. The test I was trying to do was successful after spending few hours and changes my previous code.
Changes are follows:
1) Now using UnitofWork in my controller instead of a redundant service.
2) Added a parameter less constructor to the GenericRepository Class.(with out any DBContext!),because it will requied a DBContext as a parameter in Constructor,which can not be substituted by supplying a Mocked DBContext.
GenericRepository:
public class GenericRepository where TEntity : class
{
internal DbContext _context;
internal DbSet<TEntity> dbSet;
public GenericRepository(DbContext context)
{
this._context = context;
this.dbSet = context.Set<TEntity>();
}
public GenericRepository() //newly added!
{
}
...............
Complete Test
[TestMethod]
public void Index_Return_OneModel_WhenCalling()
{
//arrange
AutoMapperExtension automapper = new AutoMapperExtension();
var moqentities = new Mock<SetupEntities>();
List<CompanyInformation> list =new List<CompanyInformation>();
list.Add(new CompanyInformation{ CompanyName = "a", CompanyAddress = "aa", Id = 1});
list.Add(new CompanyInformation { CompanyName = "b", CompanyAddress = "b", Id = 2 });
var unitOfWork = new Mock<UnitOfWork>(moqentities.Object);
unitOfWork.Setup(d => d.CompanyRepository).Returns(new GenericRepository<CompanyInformation>());
unitOfWork.Setup(d => d.CompanyRepository.GetAll()).Returns(list.AsQueryable());
var controller = new CompanyInformationController(unitOfWork.Object);
//Act
var result =(ViewResult) controller.Index();
var model =(CompanyInformationViewModel) result.ViewData.Model;
//Assert
Assert.AreEqual(1, model.Id);
}
The best way is to create an interface for XService. If that is not possible for some reason (if XService is a third party class that doesn't implement an interface), then consider wrapping the functionality in a wrapperclass that does have an interface.

asp.net mvc repository pattern with service layer, when to mix entities in the repositories?

I'm building a new project off the service repository pattern detailed here. It seems to work well in the most basic of examples. In more complex scenarios is it acceptable to mix the objects in the service \ repository layers?. For example say there is a User repository and service and I want to be able to create an audit for the creation of a user, I would think this would go in the service layer.
If I follow the article the service automatically creates the user repository object in the constructor. Adding a audit would mean adding audit CRUD methods to the user repository? Does that make sense to do that?
public UserService(IValidationDictionary validationDictionary, IUserRrepository repository)
{
_validatonDictionary = validationDictionary;
_repository = repository;
}
in my experience you dont need repositories for each entity type. Just create one repository for the whole model, and then use linq queries over it. EF already provides implementation of that repository, you can create a custom interface like shown below and implement it over that repository ..
public interface IDataContext
{
void Add<T>(T entity) where T : BaseEntity;
void Delete<T>(T entity) where T : BaseEntity;
IQueryable<T> Find<T>(Expression<Func<T, bool>> where) where T : BaseEntity;
int SaveChanges()
}
where your base entity is your base class for all repositories.
most of the linq you would write would be pretty straighforward, but for the complicated ones, just write Utility classes
in our implementation the class derived from DbContext implements this interface, and all the auditing is done through the Save Method using the ChangeTracker
A sample implementation of EF 4.2 is below ...
public class MyContext : DbContext, IDataContext
{
static MyContext ()
{
Database.SetInitializer<MyContext >(null);
}
public T GetById<T>(int id) where T : BaseEntity
{
return this.Set<T>().SingleOrDefault(i => i.Id == id);
}
public void Add<T>(T entity) where T : BaseEntity
{
this.Set<T>().Add(entity);
}
public void Delete<T>(T entity) where T : BaseEntity
{
this.Set<T>().Remove(entity);
}
public IQueryable<T> Find<T>(System.Linq.Expressions.Expression<Func<T, bool>> where) where T : BaseEntity
{
return this.Set<T>().Where(where);
}
public override int SaveChanges()
{
this.SetAuditValues();
return base.SaveChanges();
}
private void SetAuditValues()
{
var addedEntries = this.ChangeTracker.Entries().Where(e => e.State == System.Data.EntityState.Added);
var currentUser = this.GetCurrentUser();
foreach (var addedEntry in addedEntries)
{
var entity = addedEntry.Entity as BaseEntity;
if (entity != null)
{
entity.CreateDateTime = DateTime.Now;
entity.CreateUser = currentUser;
entity.ModDateTime = DateTime.Now;
entity.ModUser = currentUser;
}
}
var modifiedEntries = this.ChangeTracker.Entries().Where(e => e.State == System.Data.EntityState.Modified);
foreach (var modEntry in modifiedEntries)
{
var entity = modEntry.Entity as BaseEntity;
if (entity != null)
{
entity.ModDateTime = DateTime.Now;
entity.ModUser = currentUser;
}
}
}
}
You can surely have one repository/service layer handle more than one entity if it falls within the purpose or domain of that service. Generally in simple examples - you are correct, you don't see this but there is no reason you can include another entity.
Now in regards to your audit, why not just call off to your audit service layer instead of including an audit object (if thats what you meant)

ASP.Net MVC 3 - unitOfWork.Commit() not saving anything

I created a web application using ASP.Net MVC 3 and EF 4.1, and I am using the UnitOfWork pattern, but nothing is getting committed to the database. All this is quite new to me, and I don't know where to start to resolve this issue.
I based myself on this post to create my web application:
http://weblogs.asp.net/shijuvarghese/archive/2011/01/06/developing-web-apps-using-asp-net-mvc-3-razor-and-ef-code-first-part-1.aspx
The final code, which can be obtained here also has a service layer and the UnitOfWOrk is being injected into the services.
Instead of using the custom injector based on Unity 2 as they are in that project, I am using Unity.Mvc3.
Here is my IUnitOfWork class:
public interface IUnitOfWork
{
void Commit();
}
And here is my UnitOfWork class:
public class UnitOfWork : IUnitOfWork
{
private readonly IDatabaseFactory databaseFactory;
private MyProjectContext dataContext;
public UnitOfWork(IDatabaseFactory databaseFactory)
{
this.databaseFactory = databaseFactory;
}
protected MyProjectContext DataContext
{
get { return dataContext ?? (dataContext = databaseFactory.Get()); }
}
public void Commit()
{
DataContext.Commit();
}
}
And here is how one of my service class look like:
public class RegionService : IRegionService
{
private readonly IRegionRepository regionRepository;
private readonly IUnitOfWork unitOfWork;
public RegionService(IRegionRepository regionRepository, IUnitOfWork unitOfWork)
{
this.regionRepository = regionRepository;
this.unitOfWork = unitOfWork;
}
...
}
At start-up, my UnitOfWork component is being registered like this:
container.RegisterType<IUnitOfWork, UnitOfWork>();
Now, no matter whether I try to insert, update or delete, no request is being sent to the database. What am my missing here?
UPDATE:
Here is the content of DataContext.Commit():
public class MyProjectContext : DbContext
{
public DbSet<Region> Regions { get; set; }
public virtual void Commit()
{
base.SaveChanges();
}
}
And here is databaseFactory.Get():
public interface IDatabaseFactory : IDisposable
{
MyProjectContext Get();
}
UPDATE #2:
Using the debugger, I am noticing that my Region service and controller constructors are getting called once when performing only a select, but they are called twice when performing an update. Is this normal?
Ok, I found the culprit. It has to do with how I was registering my database factory.
Instead of
container.RegisterType<IDatabaseFactory, DatabaseFactory>();
I needed
container.RegisterType<IDatabaseFactory, DatabaseFactory>(new HierarchicalLifetimeManager());
I found the information on this web site:
http://www.devtrends.co.uk/blog/introducing-the-unity.mvc3-nuget-package-to-reconcile-mvc3-unity-and-idisposable
That's an awfully complex implementation of Unit of Work. I actually prefer this one:
http://azurecoding.net/blogs/brownie/archive/2010/09/22/irepository-lt-t-gt-and-iunitofwork.aspx
Much simpler, and much more flexible. Although you do have to work out a few things for yourself.
May just be a typo but in UnitOfWork your private MyProjectContext is called dataContext (lowercase d)
But in your commit method your calling DataContext.Commit. Any chance that's actually calling a static method that you didn't intend to call? More likely a typo but thought I'd point it out.
+1 for an overly complex implementation of UnitOfWork.

Issues with my MVC repository pattern and StructureMap

I have a repository pattern i created on top of the ado.net entity framework. When i tried to implement StructureMap to decouple my objects, i kept getting StackOverflowException (infinite loop?). Here is what the pattern looks like:
IEntityRepository where TEntity : class
Defines basic CRUD members
MyEntityRepository : IEntityRepository
Implements CRUD members
IEntityService where TEntity : class
Defines CRUD members which return common types for each member.
MyEntityService : IEntityService
Uses the repository to retrieve data and return a common type as a result (IList, bool and etc)
The problem appears to be with my Service layer. More specifically with the constructors.
public PostService(IValidationDictionary validationDictionary)
: this(validationDictionary, new PostRepository())
{ }
public PostService(IValidationDictionary validationDictionary, IEntityRepository<Post> repository)
{
_validationDictionary = validationDictionary;
_repository = repository;
}
From the controller, i pass an object that implements IValidationDictionary. And i am explicitly calling the second constructor to initialize the repository.
This is what the controller constructors look like (the first one creates an instance of the validation object):
public PostController()
{
_service = new PostService(new ModelStateWrapper(this.ModelState));
}
public PostController(IEntityService<Post> service)
{
_service = service;
}
Everything works if i don't pass my IValidationDictionary object reference, in which case the first controller constructor would be removed and the service object would only have one constructor which accepts the repository interface as the parameter.
I appreciate any help with this :) Thanks.
It looks like the circular reference had to do with the fact that the service layer was dependent on the Controller's ModelState and the Controller dependent on the Service layer.
I had to rewrite my validation layer to get this to work. Here is what i did.
Define generic validator interface like below:
public interface IValidator<TEntity>
{
ValidationState Validate(TEntity entity);
}
We want to be able to return an instance of ValidationState which, obviously, defines the state of validation.
public class ValidationState
{
private readonly ValidationErrorCollection _errors;
public ValidationErrorCollection Errors
{
get
{
return _errors;
}
}
public bool IsValid
{
get
{
return Errors.Count == 0;
}
}
public ValidationState()
{
_errors = new ValidationErrorCollection();
}
}
Notice that we have an strongly typed error collection which we need to define as well. The collection is going to consist of ValidationError objects containing the property name of the entity we're validating and the error message associated with it. This just follows the standard ModelState interface.
public class ValidationErrorCollection : Collection<ValidationError>
{
public void Add(string property, string message)
{
Add(new ValidationError(property, message));
}
}
And here is what the ValidationError looks like:
public class ValidationError
{
private string _property;
private string _message;
public string Property
{
get
{
return _property;
}
private set
{
_property = value;
}
}
public string Message
{
get
{
return _message;
}
private set
{
_message = value;
}
}
public ValidationError(string property, string message)
{
Property = property;
Message = message;
}
}
The rest of this is StructureMap magic. We need to create validation service layer which will locate validation objects and validate our entity. I'd like to define an interface for this, since i want anyone using validation service to be completely unaware of the StructureMap presence. Besides, i think sprinkling ObjectFactory.GetInstance() anywhere besides the bootstrapper logic a bad idea. Keeping it centralized is a good way to insure good maintainability. Anyway, i use the decorator pattern here:
public interface IValidationService
{
ValidationState Validate<TEntity>(TEntity entity);
}
And we finally implement it:
public class ValidationService : IValidationService
{
#region IValidationService Members
public IValidator<TEntity> GetValidatorFor<TEntity>(TEntity entity)
{
return ObjectFactory.GetInstance<IValidator<TEntity>>();
}
public ValidationState Validate<TEntity>(TEntity entity)
{
IValidator<TEntity> validator = GetValidatorFor(entity);
if (validator == null)
{
throw new Exception("Cannot locate validator");
}
return validator.Validate(entity);
}
#endregion
}
I'm going to be using validation service in my controller. We could move it to the service layer and have StructureMap use property injection to inject an instance of controller's ModelState to the service layer, but i don't want the service layer to be coupled with ModelState. What if we decide to use another validation technique? This is why i'd rather put it in the controller. Here is what my controller looks like:
public class PostController : Controller
{
private IEntityService<Post> _service = null;
private IValidationService _validationService = null;
public PostController(IEntityService<Post> service, IValidationService validationService)
{
_service = service;
_validationService = validationService;
}
}
Here i am injecting my service layer and validaton service instances using StructureMap. So, we need to register both in StructureMap registry:
ForRequestedType<IValidationService>()
.TheDefaultIsConcreteType<ValidationService>();
ForRequestedType<IValidator<Post>>()
.TheDefaultIsConcreteType<PostValidator>();
That's it. I don't show how i implement my PostValidator, but it's simply implementing IValidator interface and defining validation logic in the Validate() method. All that's left to do is call your validation service instance to retrieve the validator, call the validate method on your entity and write any errors to ModelState.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "PostId")] Post post)
{
ValidationState vst = _validationService.Validate<Post>(post);
if (!vst.IsValid)
{
foreach (ValidationError error in vst.Errors)
{
this.ModelState.AddModelError(error.Property, error.Message);
}
return View(post);
}
...
}
Hope i helped somebody out with this :)
I used a similar solution involving a generic implementor of IValidationDictionary uses a StringDictionary and then copied the errors from this back into the model state in the controller.
Interface for validationdictionary
public interface IValidationDictionary
{
bool IsValid{get;}
void AddError(string Key, string errorMessage);
StringDictionary errors { get; }
}
Implementation of validation dictionary with no reference to model state or anything else so structuremap can create it easily
public class ValidationDictionary : IValidationDictionary
{
private StringDictionary _errors = new StringDictionary();
#region IValidationDictionary Members
public void AddError(string key, string errorMessage)
{
_errors.Add(key, errorMessage);
}
public bool IsValid
{
get { return (_errors.Count == 0); }
}
public StringDictionary errors
{
get { return _errors; }
}
#endregion
}
Code in the controller to copy the errors from the dictionary into the model state. This would probably be best as an extension function of Controller.
protected void copyValidationDictionaryToModelState()
{
// this copies the errors into viewstate
foreach (DictionaryEntry error in _service.validationdictionary.errors)
{
ModelState.AddModelError((string)error.Key, (string)error.Value);
}
}
thus bootstrapping code is like this
public static void BootstrapStructureMap()
{
// Initialize the static ObjectFactory container
ObjectFactory.Initialize(x =>
{
x.For<IContactRepository>().Use<EntityContactManagerRepository>();
x.For<IValidationDictionary>().Use<ValidationDictionary>();
x.For<IContactManagerService>().Use<ContactManagerService>();
});
}
and code to create controllers is like this
public class IocControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return (Controller)ObjectFactory.GetInstance(controllerType);
}
}
Just a quick query on this. It's helped me out quite a lot so thanks for putting the answer up, but I wondered which namespace TEntity exists in? I see Colletion(TEntity) needs System.Collections.ObjectModel. My file compiles without anything further but I see your TEntity reference highlighted in Blue which suggests it has a class type, mine is Black in Visual Studio. Hope you can help. I'm pretty keen to get this working.
Have you found any way to seperate validation into the service layer at all? My gut tells me that validating in the Controller is a bit smelly but I've looked high and low to find a way to pass validation error messages back to the controller without tightly coupling the service layer to the controller and can't find anything. :(
Again, thanks for the great post!
Lloyd

Resources