windsor resolve dependency based on calling controller - asp.net-mvc

Let's say I have a (crappy pseudo code):
interface IUserService
{
....
User CreateUser(bunch of parameters)
....
}
With one implementation that get's injected into a bunch of different controllers.
The concrete UserService is injected with a
interface IHRService
{
bool ValidateInfo(user _user)
}
This is for additional/optional validation and has at least 2 implementations. ValidateInfo is called from UserService's CreateUser function. I want to inject different IHRService into UserService based on what controller is calling the UserService - this is so I can call the same CreateUser function from multiple different screens and be able to skip the additional validation in one but not the other.
Is something like this possible with windsor or am I going about this the wrong way? Should I get the correct IHRService inside of the particular controller then pass that into the CreateUser function?

I don't know if I understood you well but it seems that you could inject into UserService and abstract factory that creates a concret implementation of IHRService depending on some options at runtime. Windsor deals with abstract factories very well for that scenarions. Does it make sense ?

Related

Partially mocking an ASP.Net MVC action method in Rhino Mock?

I'm new to Rhino, and wondered how to mock a local variable/object inside a method of a class I'd also be mocking. In this case I'd be doing it with an ASP.Net MVC controller & action method.
Here's what the controller looks like, simplified:
public class HomeController : Controller {
public myObjectType myMockedObject; //I want to mock this
public myNonMockedObject; //don't want to mock this
public ViewResult Index() {
//call various methods on the mocked and nonmocked members
return View();
}
}
In other words, I'd like to create a mock home controller and mock some local variables within it and their methods-- but not all of them. Is this possible using Rhino?
You can inject these through constructor parameters. Just write constructor that takes myObjectType as parameter. Within this constructor just initialize your fields.
Note1: in case to run MVC, you will need also parameterless ctro, or modify ConstructorFactory (e.g. here https://www.codeproject.com/Articles/560798/ASP-NET-MVC-Controller-Dependency-Injection-for-Be). Or just think about using some IoC container (e.g. https://www.nuget.org/packages/Unity/) that can inject whatever you want inside the controller (mock or normal class).
Note2: you should extract an interface from myObjectType class and mock that interface instead of concrete class (Rhino handles that better).
Note3: I am usually trying to put all the logic (and test that separately) outside of controller since it is quite tough to test the controller (you need to initialize a lot of stuff there what involves another mocking).

ASP.net MVC -How to use castle windsor's capability to resolve an object inside the view

I have the requirement where I need to make a call to my service from inside of my view. The service I need to call has dependencies to my repositories.
So instead of doing like -
IUserService _userService = new UserService(new UserRepository() );
I would like to obtain the _userService object from Windsor, as it already has all the dependencies resolved.
How can I achieve this ?
The viewwhere I need to call the IUserService is _layout.cshtml inside the Shared Folder. There is no controller specific to this. So where should I be injecting the dependency from?
The functionality I need inside the view is to check for Role based access which I have implemented via UserService. I have 2 choices -
1. Either to use COntext.User.IsInRole inside my view (which is not a testable piece of code)
2. Or call the my UserService from view (which is supported by tests).
I had to choose lesser of two evils so I went with the 2nd choice.
Any inputs will be highly appreciated.
You asked for input. IMO you should not be making calls to a repository from within a view.
I can think of two better options.
Option 1
Put the users roles into a ViewModel which you then pass to the view. Then you query the ViewModel for the roles.
Option 2
Call a ChildAction on your AccountController and return a partial view.
Something like this:
In your View:
Html.Action("GetUserRoles", "Account");
In your Controller:
[ChildActionOnly]
[Transaction]
public PartialViewResult GetUserRoles(string userId)
{
var viewModel = userService.GetRolesForUser(userId);
return PartialView(viewModel);
}
Now you can just inject IUserService via the Controller constructor.
IMO Appart from simple iterations and similar stuff, Views should not contain any code, especially not data access code. That's the whole premise of the MVC pattern.

DDD and constructor explosion

I'm practicing DDD with ASP.NET MVC and come to a situation where my controllers have many dependencies on different services and repositories, and testing becomes very tedious.
In general, I have a service or repository for each aggregate root. Consider a page which will list a customer, along with it's orders and a dropdown of different packages and sellers. All of those types are aggregate roots. For this to work, I need a CustomerService, OrderService, PackageRepository and a UserRepository. Like this:
public class OrderController {
public OrderController(Customerservice customerService,
OrderService orderService, Repository<Package> packageRepository,
Repository<User> userRepository)
{
_customerService = customerService
..
}
}
Imagine the number of dependencies and constructor parameters required to render a more complex view.
Maybe I'm approaching my service layer wrong; I could have a CustomerService which takes care of all this, but my service constructor will then explode. I think I'm violating SRP too much.
I think I'm violating SRP too much.
Bingo.
I find that using a command processing layer makes my applications architecture cleaner and more consistent.
Basically, each service method becomes a command handler class (and the method parameters become a command class), and every query is also its own class.
This won't actually reduce your dependencies - your query will likely still require those same couple of services and repositories to provide the correct data; however, when using an IoC framework like Ninject or Spring it won't matter because they will inject what is needed up the whole chain - and testing should be much easier as a dependency on a specific query is easier to fill and test than a dependency on a service class with many marginally related methods.
Also, now the relationship between the Controller and its dependencies is clear, logic has been removed from the Controller, and the query and command classes are more focused on their individual responsibilities.
Yes, this does cause a bit of an explosion of classes and files. Employing proper Object Oriented Programming will tend to do that. But, frankly, what's easier to find/organize/manage - a function in a file of dozens of other semi-related functions or a single file in a directory of dozens of semi-related files. I think that latter hands down.
Code Better had a blog post recently that nearly matches my preferred way of organizing controllers and commands in an MVC app.
Well you can solve this issue easily by using the RenderAction. Just create separate controllers or introduce child actions in those controllers. Now in the main view call render actions with the required parameters. This will give you a nice composite view.
Why not have a service for this scenario to return a view model for you? That way you only have one dependency in the controller although your service may have the separate dependencies
the book dependency injection in .net suggests introducing "facade services" where you'd group related services together then inject the facade instead if you feel like you have too many constructor parameters.
Update: I finally had some available time, so I ended up finally creating an implementation for what I was talking about in my post below. My implementation is:
public class WindsorServiceFactory : IServiceFactory
{
protected IWindsorContainer _container;
public WindsorServiceFactory(IWindsorContainer windsorContainer)
{
_container = windsorContainer;
}
public ServiceType GetService<ServiceType>() where ServiceType : class
{
// Use windsor to resolve the service class. If the dependency can't be resolved throw an exception
try { return _container.Resolve<ServiceType>(); }
catch (ComponentNotFoundException) { throw new ServiceNotFoundException(typeof(ServiceType)); }
}
}
All that is needed now is to pass my IServiceFactory into my controller constructors, and I am now able to keep my constructors clean while still allowing easy (and flexible) unit tests. More details can be found at my blog blog if you are interested.
I have noticed the same issue creeping up in my MVC app, and your question got me thinking of how I want to handle this. As I'm using a command and query approach (where each action or query is a separate service class) my controllers are already getting out of hand, and will probably be even worse later on.
After thinking about this I think the route I am going to look at going is to create a SerivceFactory class, which would look like:
public class ServiceFactory
{
public ServiceFactory( UserService userService, CustomerService customerService, etc...)
{
// Code to set private service references here
}
public T GetService<T>(Type serviceType) where T : IService
{
// Determine if serviceType is a valid service type,
// and return the instantiated version of that service class
// otherwise throw error
}
}
Note that I wrote this up in Notepad++ off hand so I am pretty sure I got the generics part of the GetService method syntactically wrong , but that's the general idea. So then your controller will end up looking like this:
public class OrderController {
public OrderController(ServiceFactory factory) {
_factory = factory;
}
}
You would then have IoC instantiate your ServiceFactory instance, and everything should work as expected.
The good part about this is that if you realize that you have to use the ProductService class in your controller, you don't have to mess with controller's constructor at all, you only have to just call _factory.GetService() for your intended service in the action method.
Finally, this approach allows you to still mock services out (one of the big reasons for using IoC and passing them straight into the controller's constructor) by just creating a new ServiceFactory in your test code with the mocked services passed in (the rest left as null).
I think this will keep a good balance out the best world of flexibility and testability, and keeps service instantiation in one spot.
After typing this all out I'm actually excited to go home and implement this in my app :)

Right way to derive controllers from a base controller

I tend to consume the same set of repositories from all my controllers. That is, I instantiate repository objects (with IoC) in every controller.
I think I could derive my controllers from a base controller that could instantiate these objects in one place. Could you point me to the right of doing this? Thank you for your help.
You have a number of options, and which one is "the right way" is really up to you and how your system functions overall. There could be performance issues for various instantiated objects that need to be considered, etc.
One option could be as simple as:
public class BaseController
{
protected ISomeRepository myRepository = IoCContainer.Resolve<ISomeRepository>();
}
public class MyController : BaseController { }
Additionally, you could move the initialization to the base controller's constructor rather than have it be inline like that.
Another option might be to late-bind the repositories, if having them all incurs a performance hit (weighed carefully with the hit of instantiating them) and on average they aren't always needed:
public class BaseController
{
private ISomeRepository _myRepository;
protected ISomeRepository myRepository
{
get
{
if (_myRepository == null)
_myRepository = IoCContainer.Resolve<ISomeRepository>();
return _myRepository;
}
}
}
There are probably more options available to you, it all depends on your setup. How your particular IoC container works may also play heavily into your design decision.
(Note that I reference the IoCContainer directly here for brevity and simplicity, but I recommend abstracting out the container behind a service locator so that you don't have so many references to the container itself.)
Actually, it depends on what kind of tasks should those "Common Repositories" complete. If they are directly relate to what Action supposed to do - maybe that is okay. But you'll anyway face some problems with IoC-resolution. In order to avoid injecting those repositories all the time for each new Repo you'll have to make a dependency on Service Locator in your base controller. Which isn't good thing.
If those Repositories are ther efor something that is orthogonal to what Action is going to do - then it is more like AOP-kinda logic, so I'd better use Action Filters for that or RenderAction.
In common case, I'd try to avoid layer supertype dependencies as well as would prefer Composition over Inheritance.

MVP : other constructor's parameters than view and model?

I'm experimenting with implementing a lightweight mvp framework with Delphi 2009.
Views are passive but supports databinding (via an interface property).
I'm facing a dilemna:
I've several very similar views/presenter/model triad, ie :
order form and a customer form = behavior and logic is the same but the datasource for databinding is different and the form title too. the datasource is a common property for all my models so it's not a problem, to set the form title, I'm forced to hard code it in my presenter InitView method
All is working good, but I'm in a situation where I have several simple mvp triads very similar. I want to refactor it but in that case I will have to pass some parameters to the mvp constructor.
So far I'm doing like that :
Create the view
Create the model
Create the presenter and inject model and view in the constructor
In fact, I'm facing a choice :
Having some very generic views/presenter, use them like that but inject 1 or 2 parameters in the constructor
Having some views/presenters superclass, and derive all my similar view/presenter from them and set some specific values in the overriden methods.
Can you give me some hints / advices ?
(sorry if i'm not very clear)
Fred,
I will choose 1 & 2 in a way that is having an abstract views/presenters that contain generic behaviors and creates abstract functions that could be possible specific behaviors implemented by subclasses.
for example,
public abstract class AbstractPresenter{
// subclass will be implemented
public abstract void InitView(Model model, View view);
}
and then you might have sublcasses, OrderFormPresenter and CustomerFormPresneter extends from AbstractPresenter.
public OrderFormPresenter extends AbstractPresenter{
public void InitView(Model model, View, view){
// do something specific values
}
}
public CustomerFormPresenter extends AbstractPresenter{
public void InitView(Model model, View, view){
// do something specific values
}
}
Please, correct me if it goes wrong direction.
I hope it helps.
Tiger
I'd create a generic view/presenter with parameters and subclass only when needed.
Another approach (and the way that I once solved this problem so it worked very well) is to build a generic "metadata" interface into the model, and the view (either interfaces, or via class inheritance) then use these generic interfaces in your presenter. I chose to use inheritance for my model, and interfaces for my view (was easer to slap a interface on an existing form than to require form/frame inheritance across the board). In my solution, the constructor for the presenter took 3 parameters, the model, the view and the "MVP name". I used the name of the MVP to load settings which were specific to the current scenario.

Resources