Injecting dependency into CustomAttribute using Castle Windsor - c#

In my ASP.Net MVC application I have implemented a Custom ActionFilter to Authorize users.
I use CastleWindsor to provide dependency injection into all of the controllers as follows:
protected virtual IWindsorContainer InitializeServiceLocator()
{
IWindsorContainer container = new WindsorContainer();
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));
container.RegisterControllers(typeof(HomeController).Assembly);
ComponentRegistrar.AddComponentsTo(container);
ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
return container;
}
Within my CustomAttribute, I need a dependency that is used by all of my controllers, however I am unable to user Constructor based injection in an attribute.
So what's the cleanest way out here? How can I provide the dependency?

OK - this seems to be a duplicate of Database injection into a validation attribute with ASP MVC and Castle Windsor which has been answered.
Also How do I use Windsor to inject dependencies into ActionFilterAttributes.
Having read through the above, and the referenced articles - the key one for me is http://weblogs.asp.net/psteele/archive/2009/11/04/using-windsor-to-inject-dependencies-into-asp-net-mvc-actionfilters.aspx for anyone else who is interested.

You can't. Attributes are metadata. Putting behaviour into them is wrong. Putting dependencies is even worse.
Use your attribute as marker to denote objects to which you want to apply the behavior and implement the behavior elsewhere.
In MVC elsewhere usually means a custom action invoker that uses data from the attribute to provide the behavior you need.

Related

Dependency injection in ASP.NET WebAPI: IHttpControllerActivator vs. IDependencyResolver

Recently I came across this discussion.
In ASP.NET WebAPI, when we need to integrate a custom inversion of control/dependency injection container, we need to go with two different strategies:
Implement IHttpControllerActivator, which is an extension point to fully control controller's life-cycle. That is, we can define how a controller is instantiated. At this point, we can resolve the controller using an inversion of control container and let it use its own dependency injection approach.
Implement IDependencyResolver, where we can define how to resolve dependency injections.
In my current projects I went the IHttpControllerActivator way, and since I'm using Castle Windsor as inversion of control container, I can fully control object life cycle from its container configuration, and I can decide how controllers are resolved, and the scope of its recursively-injected dependencies defining that they die once the controller ends its life (i.e. when the request ends).
While some of these features can be achieved with IDependencyResolver implementations, I feel that IHttpControllerActivator is the best way to integrate inversion of control and dependency injection in ASP.NET Web API, because I believe that I prefer to stay as abstract as possible and stick with Castle Windsor configuration model in terms of inversion of control and dependency injection.
The main drawback with the IHttpControllerActivator approach is you need to register all controllers in the container while IDependencyResolver still gives the responsibility of resolving the controller to ASP.NET Web API pipeline (for me, this hasn't been a big issue, I just used Castle Windsor's Classes.FromAssembly to configure all controllers deriving ApiController).
Do I ignore any other drawbacks that would make the IDependencyResolver approach more appropiate?
The IHttpControllerActivator approach primarily has an advantage over the IDependencyResolver approach because of the context provided, as excellently described in the following blog post: http://blog.ploeh.dk/2012/09/28/DependencyInjectionandLifetimeManagementwithASP.NETWebAPI/.
However, in most easier scenarios, it simply does not pay back the extra effort to manually register everything. Using the IDependencyResolver approach in many situations just 'does the trick'. Add good documentation and the larger day to day user base to that, and I myself would probably consider if I could manage using IDependencyResolver before considering IHttpControllerActivator.

Resolve dependencies in ASP.NET Web API with Simple Injector and IHttpControllerActivator

I am currently using Simple Injector to resolve dependencies into my Asp.Net Web Api projects.
From the documentation you can configure it like that:
protected void Application_Start() {
// Create the container as usual.
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();
// Register your types, for instance using the scoped lifestyle:
container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);
// This is an extension method from the integration package.
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
container.Verify();
GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container);
// Here your usual Web API configuration stuff.
}
The main points here are to register the Web Api controllers and set a custom dependency resolver.
However I've just read these article from Mark Seemann on how to configure dependency injection in Asp.Net Web Api:
Dependency Injection and Lifetime Management with ASP.NET Web API
Dependency Injection in ASP.NET Web API with Castle Windsor
From these articles, I've learnt that there is a better option than implementing IDependencyResolver to resolve Web Api dependencies.
This other option is to create an implementation of the IHttpControllerActivator that acts as an Adapter over the IoC Container.
Here is the implementation I've coded using SimpleInjector:
public class SimpleInjectorControllerActivator : IHttpControllerActivator
{
private readonly Container _container;
public SimpleInjectorControllerActivator(Container container)
{
_container = container;
}
public IHttpController Create(HttpRequestMessage request,
HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
request.RegisterForDispose(_container.BeginExecutionContextScope());
return (IHttpController)_container.GetInstance(controllerType);
}
}
and in the Application_Start method, I've replaced this line:
GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container);
by this line :
GlobalConfiguration.Configuration.Services.Replace(
typeof(IHttpControllerActivator),
new SimpleInjectorControllerActivator(container));
I would like to know if the implementation of the IHttpControllerActivator is valid and also if this approach is valid and will work as good as the normal one ?
Yes, your implementation is valid.
Only be careful not to use both the SimpleInjectorWebApiDependencyResolver and the SimpleInjectorControllerActivator in the same application. Both start an ExecutionContextScope which could lead to having two scopes within the same web request, so they are mutually exclusive.
A general advantage of using a controller activator over the dependency resolver is that the dependency resolver contract forces the adapter to return null when a service can't be created. This is a very common problem that developers run into, and it often causes the confusing controller does not have a default constructor exception. This problem does not exist when using an IHttpControllerActivator, since the contract forces you to return a value or throw an exception.
The Simple Injector Web API integration project however, prevents this problem with dependency resolver, by never returning null (but throwing an exception instead) in case the requested service is an API controller (and thereby implicitly breaking the IDependencyResolver's contract).
An advantage of using the SimpleInjectorDependencyResolver is that it becomes easier to create message handlers that operate within the execution context scope, since you can trigger the creation of this scope by calling request.GetDependencyScope() method. With the current implementation, the scope just gets started at the time that the controller gets created, which is after you run the handlers. Changing this isn't that hard, but involves changing your controller activator and have an outermost handler that starts the execution context scope (or again falling back on a dependency resolver that manages the execution context scope).
One of the arguments of Mark Seemann is that it becomes hard to pass context around, which is a very valid point, as long as your components don't require this context during construction. But this is not a problem you'll experience when using Simple Injector, because there is an extension method that helps you with accessing the HttpRequestMessage. So although the IDependencyResolver abstraction isn't designed for getting the contextual information, there are ways to get this contextual information.
In the past we decided to go with an adapter for the IDependencyResolver, mainly because this was the common practice with all DI containers. I partly regret this decision, but using the SimpleInjectorDependencyResolver is now usually the easiest way of plugging in Simple Injector into Web API. We considered adding a SimpleInjectorControllerActivator as well, but this had no practical benefit for most users, while we still would had to document when to use what. So we decided to stick with the dependency resolver adapter; an adapter for the activator is easily created for anyone who needs it, as you can see.
For ASP.NET Core however, we went into a different direction, and as you can see in the documentation, the integration package actually contains a SimpleInjectorControllerActivator out of the box. In ASP.NET Core, the controller activator is the perfect interception point and due to the OWIN-like pipeline, a scope can be easily wrapped around a request. So with ASP.NET Core, the advised practice is to use the controller activator as interception point.

How to programatically register a RoleProvider in ASP.NET MVC 5?

I've implemented a role provider using dependency injection technique. So as the class doesn't have a parameterless constructor (a repository is injected there), the usual web.config registration method doesn't work.
I was trying to register the provider manually in my Global.asax application start event like this, but I get a NotSupportedException stating that the Roles.Providers collection cannot be modified.
Roles.Providers.Clear();
Roles.Providers.Add(new RepositoryRoleProvider(new MyRepositoryFactory()));
What is the proper way to register a role provider without it having a parameterless constructor?
There is an article that describes how to implement and register a role provider. It is using the "provider pattern".
Since it is using the "provider pattern", it is not possible to use constructor injection because the constructor is constrained to use a default public constructor.
So, your options are not good:
Instantiate your repository factory in the Initialize method (note if it has a default constructor, you could put its type string in the config file and use Activator.CreateInstance to construct it).
Use a static reference to your DI container (service locator) to resolve the dependency.
If you have a choice, it would be better to use ASP.NET Identity instead of membership, since it is much more DI friendly.

Windsor Ioc avoid call resolve all the time

Guys I need your help I am using Castle Project Windsor IoC container in my C# Winforms application. I have services classes which has DI by constructor passing in implementing Repositories. I used Windsor to register them all Component.Register(...etc but everytime I use my service class I am calling resolve. for example:
var employeeService = container.Resolve....etc
is there any other way not having to call resolve all the time?
in ASP.NET you can just register them all then set the Controller factory: ControllerBuilder.Current.SetControllerFactory(new WindsorIoCFactory());
with this I can just use my controllers(using services) directly without calling resolve. how do you do this in winforms?
You should use a Composition Root approach.
In short, you should use Resolve only once at the App-StartUp basically resolving the MainView and through that you should be able to obtain all views(most likely through a TypedFactory) and their dependencies with no explicit Resolve call.
Service locator approach, as per comment link, is a deprecable anti-pattern specially when Composition Root can be used instead.
On the windsor wiki you'll find a sample based on a Silverlight app, very close to a Winform scenario.

ASP MVC DependencyResolver with UnityContainer for Unit testing

I'm building an ASP MVC 3 application in which I use Unity as IOC container and I register it on the DependencyResolver. In my controller I can then do this:
DependencyResolver.Current.GetService(GetType(IViewAllPersonsHandler))
Then when I write my unit tests I redefine my mappings in my test to use mocked objects.
A colleague of mine told me that doing this is considered as an Anti Pattern.
Can anyone tell me whether this is the case and why?
I know that normally I should inject my dependencies in the constructor, but as my controller grows the constructors parameters get lengthy.
Thx
Most folks consider the service locator pattern an anti-pattern. Probably since one can get around it with some leg-work.
If you are doing it to limit the constructor parameters you could try something different. I use property injection. Since I use castle windsor the container injects public properties by default. Last I looked Unity did not do this and you had to use some extension to get that to work.
Other than that you could split your controller or delegate to tasks within your actions.
But I would also stay away from service locator from within you controller.
HTH
You can use System.Web.Mvc.DependencyResolver.SetResolver(resovlveDependencyMock);
It's easy with Moq:
DependencyResolver.SetResolver(Mock.Of<IServiceLocator>(s => s.GetInstance(It.IsAny<Type>()) == cacheMock.Object));

Categories