IOC on IValidationDictionary with Castle Windsor - asp.net-mvc

I'm new to Castle Windsor and am just using the latest version. I've created entries for my repositories which are working fine but I have one final dependency that I'm passing into my controller.
I've created a ModelStateWrapper which inherits from IValidationDictionary. The ModelStateWrapper takes a ModelStateDictionary in it's constructor so that in my code I can pass the following as an example:
IMembershipService _memSvc;
IValidationDictionary _validationService;
public AccountController()
{
_validationService = new ModelStateWrapper(this.ModelState);
_memSvc = new MembershipService(_validationService);
}
In my tests I can then do this using Moq:
var v = new Mock<ModelStateDictionary>();
_validationService = new ModelStateWrapper(v.Object);
_service = new MembershipService(_validationService);
I can't seem to get Castle to inject ModelState in with the ModelStateWrapper. I have no idea where to start and it seems I can't just 'ignore it' and try to manually inject as Castle is searching for dependencies and throwing me an error saying a dependency is remaining.
How do I configure Castle Windsor to use the ModelStateWrapper based off IValidationDictionary and also include ModelState as the constructor parameter?
Lloyd

It seems like you have a circular dependency (never a good thing). You can get around it by using an Abstract Factory as described in this very similar question.
However, although you may be able to solve the problem like this, it would be better to redesign the API to make the circular dependency go away. Circular dependencies often indicate a design flaw.

You're doing it wrong, and your wrongdoing has nothing to do with the container you're using.
Just do it like this, if you absolutely need to:
public AccountController(IValidationService service)
{
_validationService = service;
_memSvc = new MembershipService(_validationService);
}
then as you're registering your component, use an OnCreate method:
container.Register(
Component.For<AccountController>()
.WheveverEleseYouNeedHere()
.OnCreate((k, controller) =>
controller.ValidationService.Init(controller.ModelState)));

Related

How to solve No parameterless constructor defined for this object error in Mvc?

I am creating one demo application to learn how to use repository pattern for performing Insert operation.I am using Nop Commerce**(http://www.nopcommerce.com) **code for repository pattern
Error:No parameterless constructor defined for this object
I have seen this link:MVC: No parameterless constructor defined for this object
This is my Structure:
My Repository interface:
public partial interface IRepository<T>
{
void Insert(T entity);
}
My Service Layer:
public partial interface IEmployeeService
{
void InsertCategory(EmployeeMaster employeeMaster);
}
My Class which will implement that interface(service):
public partial class EmployeeService : IEmployeeService
{
#region Fields
private readonly IRepository<EmployeeMaster> _employeeMasterRepository;
#endregion
#region Ctor
public EmployeeService
(
IRepository<EmployeeMaster> employeeMasterRepository
)
{
this._employeeMasterRepository = employeeMasterRepository;
}
#endregion
public virtual void InsertCategory(EmployeeMaster employeeMaster)
{
if (employeeMaster == null)
throw new ArgumentNullException("employeeMaster");
_employeeMasterRepository.Insert(employeeMaster);
}
This is my controller:
public class HomeController : Controller
{
#region Fields
private readonly IEmployeeService _employeeService;
#endregion
#region Constructors
public HomeController
(
IEmployeeService employeeService
)
{
this._employeeService = employeeService;
}
#endregion
Getting Error:No parameterless constructor defined for this object
I have studied regarding this error and all the sources are saying that use Dependency injection to solve this error.
Can anybody guide me how to use dependency injection to solve this error??
Maybe you're taking as a sample a project that is too complex for you at this moment. Nopcommerce is a big and full featured product that has a lot of elements, so it easy to get lost. Not the best sample to learn how the repository pattern works, but I certainly recommend you to check it again once you have the basic concepts clear to see them used in a real scenario.
NopCommerce uses Autofac for dependency injection, a very popular IoC container. You can look for a class called DependencyRegistrar in the project Nop.Web.Framework to see how it is used, if you're curious about it. You can get more examples on how to use dependency injection with Autofac in their repository and their getting started guide.
My recommendation is to look for an easier to follow example. For starters, any of the popular IoC containers will be OK until you have your own criteria to choose one. For instance you can follow the Autofac's guide for MVC
You're correct - you'll need to use something like Unity, Ninject or Autofac to get this running.
Essentially - the steps are roughly the same regardless of the tech used.
Using unity as an example:
1) In your MVC project, use NuGet to add "Unity Bootstrapper for MVC". (right click references, manage nuget packages, search for unity online, select "Unity Bootstrapper for MVC"
This will add a few things to your project - the most interesting is the unityConfig.cs in App_start.
2) In unityConfig.cs - find RegisterTypes method
RegisterTypes is where you tell the unity container "when you need one of X, use implementation Y" - in your case "when you need an IEmployeeService, use EmployeeService"
3) In register types - add your type mappings - for example, in your case:
container.RegisterType<IEmployeeService, EmployeeService>();
AND
4) Bit more complicated: as you have IRepository and you need this to resolve your employeeService correctly you'll also have to register a generic type against a generic implementation (it's a little odd). Looking at your types, it's going to be something like:
container.RegisterType(typeof(IRepository<>), typeof(Repository<>));
(You'll need to resolve the namespaces according to your projects).
So - what this is saying is...
Right MVC - when you need an IEmployeeService use employeeService, and
when you need an IRepository<>, use Repository<>
Now - because of the webActivator that was added during the NuGet installation (right next door to UnityConfig.cs), that should be it - the webActivator sets the DependencyResolver.Current to something that uses this unityContainer.
Beacause of this, MVC will now use this new unityContainer whenever it tries to instantiate your controllers, resolving the type mappings on the way.
The webActivator and unityConfig classes do alot of the heavy-lifting for you, just elaborate registerTypes and you should at least have a foot-hold in the solution.
HTH - good luck.
PS - DI itself is a massive subject - far too much for here, you'll bump into all sort of weird and wonderful things (supplying Ctor args for resolutions, lifetime management just for a start!) - it's fun, but not trivial, so you'll have to excuse me if this doesn't work "out of the box" (it's almost impractical to think it would) - this is merely just a vague attempt to give you a foothold in the subject!
For more info on unity - I suggest you read up here (Dev guide to using Unity on MSDN)

WebApi with Unity issue with parameterless constructor

I am trying to setup Unity for the first time in a WebApi project. I have added Unity.WebApi from Nuget and my UnityConfig file looks like this.
public static void RegisterComponents()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterType<ApplicationDbContext>(
new InjectionFactory(c => new ApplicationDbContext()));
//container.RegisterType<ApplicationSignInManager>();
container.RegisterType<ApplicationUserManager>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
However, if I try and call one of the default controllers, Account/Register I get an error saying ensure that I have a parameterless constructor.
I have looked at various articles that explain that the way Unity works in MVC and WebApi but as far as I can tell my config is correct? Im guessing Im missing something simple here as my installation works perfectly for constructor injection in an MVC project.
Unity will use the most greedy constructor (constructor with maximum number of parameters) when it tries to resolve your dependency, so in the case of the AccountController it has two constructors first one is parameterless and the second is with two parameters like bellow, and this what unity will try to use.
public AccountController(ApplicationUserManager userManager,
ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
{
UserManager = userManager;
AccessTokenFormat = accessTokenFormat;
}
To override this, decorate required constructor with InjectionConstructorAttribute.
Hope that helps.

Dependency injection with Global.asax

I am using dependency injection for the inject interface with the classes
I use it in the Global.asax like this
new UnityContainer().RegisterType<IBookingService, BookingService>()
and controller
IBookingService bookingService
Now the thing is I want to change the injected implementation class for an interface in the controller level
How can I do it with a controller level?
i want to do some things like this in controller level
private readonly IBookingService bookingService;
if(countryCode = SE ){
bookingService = new bookingSE();
}
else IF (countryCode = NO ){
bookingService = new bookingNO();
}
i want to use Dependency injection for this
Make sure that you use the Unity.Mvc NuGet package. This will add a App_Start\UnityConfig.cs file to your project and you can add the registrations in its RegisterTypes method as follows:
container.RegisterType<IBookingService, BookingService>();
Perhaps you are already doing this, but I wanted to make sure since your exact code example with the new UnityContainer().RegisterType will not work.
Another interesting thing that this package does can be viewed in the App_Start\UnityWebActivator.cs file:
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
This line will register the unity container as standard MVC DependencyResolver. This allows constructor injection to be applied to your controllers. With this you can define your controller as follows:
public class MyCoolController : Controller
{
private readonly IBookingService bookingService;
public MyCoolController(IBookingService bookingService)
{
this.bookingService = bookingService
}
public ActionResult Index()
{
// your usual MVC stuff here.
}
}
In almost all cases, the use of constructor injection is advised over all forms of injection so stick with constructor injection unless there is no other way. And if you think there's no other way, please to ask here at Stackoverflow. We might be able to give some feedback on your code and design.
Just call Resolve
var bookingService= container.Resolve<IBookingService>()

How should my ASP.NET MVC Controllers be aware of the repository

I'm trying to get my head around how one would unit test an ASP.NET MVC project that accesses data through a repository of some sort.
During the unit tests I'd obviously want to create a mock repository but how do I pass this mock repository to the Controller instance being tested? Also how would the actual repository, that's really connected to a database, find its way to the controller?
Do I simply do this through the constructors as I've shown below? I think this is how I should set up my controllers, but I'd like some confirmation that this is correct:
public class SampleController : Controller
{
private IRepository _repo;
//Default constructor uses a real repository
// new ConcreteRepo() could also be replaced by some static
// GetRepository() method somewhere so it would be easy to modify
//which concrete IRepository is being used
public SampleController():this(new ConcreteRepo())
{
}
//Unit tests pass in mock repository here
public SampleController(IRepository repo)
{
_repo = repo;
}
}
As everyone has already said, you'll want to use an IoC* or DI** container. But what they haven't said is why this is the case.
The idea is that a DI container will let you bypass ASP.NET MVC's default controller-construction strategy of requiring a parameterless constructor. Thus, you can have your controllers explicitly state their dependencies (as interfaces preferably). How those interfaces map to concrete instances is then the business of the DI container, and is something you will configure in either Global.asax.cs (live) or your test fixture setup (for unit testing).
This means your controller doesn't need to know anything about concrete implementations of its dependencies, and thus we follow the Dependency Inversion Principle: "High-level modules should not depend on low-level modules. Both should depend on abstractions."
For example, if you were to use AutoFac, you would do this:
// In Global.asax.cs's Application_Start
using Autofac;
using Autofac.Integration.Mvc;
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.Register<IRepository>(() => new ConcreteRepo());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
// In your unit test:
var controllerInstance = new SampleController(new InMemoryFakeRepo());
// In SampleController
public class SampleController : Controller
{
private readonly IRepository _repo;
public SampleController(IRepository repo)
{
_repo = repo;
}
// No parameterless constructor! This is good; no accidents waiting to happen!
// No dependency on any particular concrete repo! Excellent!
}
* IoC = inversion of control
** DI = dependency inversion
(the two terms are often used interchangeably, which is not really correct IMO)
Yeah, you're correct, you pass it to your constructor like you have it. By mocking IRepository your explicitly ensuring that the database dependent code doesn't get into the controller for testing, like you want.
When you actually run it, you'll want to setup your application to work with an inversion of control container to enable those dependencies to be injected into your controller (some popular ones are Ninject, StructureMap, and Windsor).
Here's a sample of testing using Moq:
private Mock<IRepository> _mockRepo;
private SampleController _controller;
[TestInit]
public void InitTest()
{
_mockRepo = new Mock<IRepository>();
_controller = new SampleController(_mockRepo.Object);
}
[Test]
public void Some_test()
{
_mockRepo.Setup(mr => mr.SomeRepoCall()).Returns(new ValidObject());
var result = _controller.SomeAction() as ViewResult;
Assert.IsNotNull(result);
}
Now you can test your actions and mock your IRepository to behave however you want.
The best answer I know is to use an Ioc Container:
http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx
I prefer Castle Windsor
With the controller dependencies passed in you can then create mocks.
We have dependencies that implement interfaces which can be mocked.
For the real one, check out ninject mvc 3 on nuget, for unit testing I prefer to use fake objects with in-memory collections of known data

Automatically set property after component creation with Autofac

Here is the example code:
public interface IService<TEntity> {
IContext Context { get; set; }
//unimportant methods
bool Validate(TEntity entity);
void Add(TEntity enttity);
}
public class UsersController : Controller {
private IService<User> _service;
public MyController(IService<User> service){
_service = service;
_service.Context = ControllerContext;
}
}
I'm using AutofacControllerFactory to create controllers in my ASP.NET MVC app.
Is it possible to eliminate this line of code in every controller's constructor:
_service.Context = ControllerContext;
In other words: is it possible to automatically set this property with ControllerContext?
It should be possible because every IService implementation has a settable IContext property.
Should I extend the AutofacControllerFactory or is there a standard way of doint this?
What you have there is a Circular Dependency.
UsersController depends on IService<User>
IService<User> depends on ControllerContext
ControllerContext depends on UsersController
No DI Container can reach into your classes' innards and control what happens there. They can set up dependencies for you and inject them into your classes from the outside. However, they can't very well deal with circular dependencies, so a better option is to redesign the API.
From here it looks very much like the Context property of IService<TEntity> is a Leaky Abstraction. A Service shouldn't need to know anything about the UI framework in which it is running.
You can often break a circular dependency by changing one of the consumers to a more event-driven architecture.
Here's an article about this sort of problem.
Here's a related answer to a ASP.NET MVC question that looks a lot like yours: Is there a good/proper way of solving the dependency injection loop problem in the ASP.NET MVC ContactsManager tutorial?
See also the answer: Dependency-Injection to resolve circular dependencies

Resources