When to allow Services to access the IoC Controller? - dependency-injection

What are the scenarios in which it's OK to allow services created via IoC to have access back to the IoC controller to access other services? It seems to me that the short answer is never, but are there situations in which it's OK or even in which it makes sense?

I think the answer is 'never', since it sounds like what you describe is service locator, which is an anti pattern

There's a rather well written article about this from Martin Fowler:
http://martinfowler.com/articles/injection.html#UsingAServiceLocator
A lot of this depends on the nature of the user of the service. If you
are building an application with various classes that use a service,
then a dependency from the application classes to the locator isn't a
big deal. In my example of giving a Movie Lister to my friends, then
using a service locator works quite well. All they need to do is to
configure the locator to hook in the right service implementations,
either through some configuration code or through a configuration
file. In this kind of scenario I don't see the injector's inversion as
providing anything compelling.

Related

ASP.NET MVC dependency injection outside the controller with Unity

I am building an ASP.NET MVC 5 application using the repository and service layer design patterns. I have used unity to inject my services into my controllers.
This works nicely and until now I have not had a need to consider instantiating any objects requiring injection of interfaces outside my controllers. However I have a need for this when configuring my application startup to setup some users in the database.
For this I wanted to user my UsersService that I've built. And it occurred to me as the application grows there will surely be other occasions when I'll want to do the same, such as calling a service from within another service.
I see that I can instantiate a Unity container and call resolve on it to get my new instance of a service:
IProductService productService = container.Resolve<IProductService>();
However this kinda smells to me, having the container leaked all over my application seems like an anti pattern. So is there a better way to do this?
Unity and other dependency injection containers automatically do this. When you inject a service into a controller, it will automatically resolve the entire dependency graph of that service. Not only can you resolve dependencies of the service and its dependencies, you should inject dependencies into the service that needs them instead of the controller.
Any class (including the controller) that has more than a handful of dependencies is a code smell that you are violating the Single Responsibility Principle, and you most likely should refactor to aggregate services.
And yes, injecting the container to any point outside of the composition root is an anti-pattern called a service locator.
As for injecting services outside of the controller, it is important to distinguish between injectables and runtime data. For example, some try to inject services into DTO objects, attributes, static classes/extension methods, and other places where it is anti-pattern for services to be injected. For these situations, it is important to properly assess the situation and refactor toward a DI-friendly solution - favoring constructor injection over other alternatives and considering a service locator as a last resort. For example, if you are trying to make an extension method with a dependent service, most likely you have some functionality that itself should be a non-static service, DTOs should never be created from a DI container, and you may have to make use of more than one extension point in MVC where you inject the container within the composition root of the application, which does not constitute a service locator.
Is it worth it? Usually. What is gained? You gain the ability to change the application much more quickly than if you have a tightly-coupled application in ways that the designer of the application may not have even anticipated. So the extra cost of ensuring the application is loosely-coupled is usually more than recouped in ongoing maintenance of the project. As a side benefit, you gain the ability to easily unit-test each component independent of the others.

Web API calling Web service

I have a .net Web API 2 application that I need to use to call an web service (asmx) just to see if the web service is up and running correctly. I am a believer in architecture, so with that in mind I am not sure where to put the call to the web service. I found a post that suggested that I put this in the repository layer. Is this the correct location for that?
I would say its more of a personal preference + project specific; IMO you can place that web service in repository if it acts as a data-store or you could place it in business layer of the service does more of a business related stuffs.
But one thing I would do for sure is to create a wrapper/abstraction over this service before using it in any layer so that:
I can inject this dependency in the layers its being used
Unit testable code - DI and mockable
No changes in the layers where this is being consumed in case there is any change in service- for eg, asmx1 to asmx2 or change in asmx service to wcf or REST etc.
Not sure whether you will be able to find a specific answer to this, this is kinda arguable subject as opinions might differ according to personal preference

Should spring security method level annotations be applied at the controller layer or the service layer?

I have been using spring security with #PreAuthorize on my controller methods. My reasoning was that I wanted the authorization check to happen predictably in one layer, and as early as possible in the request. However, I just read the spring security 3 documentation, and saw that they recommend applying method level security on the service layer (but they don't say why).
My question is: should spring security method level annotations be applied at the controller layer or the service layer? (Or "both", or "it depends"?) More importantly: why?
"It depends" :). If your application has a service layer through which all your business logic is applied then that is usually a clean place to apply your security constraints and be certain that you haven't missed out any corner cases.
Web code is generally messier, there's more of it, it changes more rapidly and you may end up calling the same service methods from multiple places. Someone might add a new controller and forget to secure it properly. Alternatively you might have different types of clients calling the same services.
But it depends on how your application is structured and what your use cases are. You may have a good argument for why you want to secure a controller.
Think in terms of code reuse. Are you going to use your service elsewhere? Not just to feed your web tier?
We also reuse our services with jms bridges so we secure our service layer.
I think the Service is the better place to use it.
Despites some problems that #PreAuthorize could create on Controller and the Spring Security FAQ recommendation to put this kind of annotation on Service, I understand that the authorization for some action is more a business rule than a responsibility for the web tier.

Using Common Service Locator outside Main Project

I recently made the jump from StructureMap to Ninject. All was smooth sailing until I realised that Ninject doesn't have a version of StructureMap's ObjectFactory (service locator).
I discovered Common Service Locator which provides the Service Locator Pattern with any IOC container including Ninject. It works great inside my 'start-up' project - e.g. WebSite. But if I try to access ServiceLocator.Current from subprojects, e.g. Core or Data it seems that CommonServiceLocator doesn't know about any of my Dependency mappings.
How do I use Common Service Locator from a sub-project?
N.B. I am aware of the debate about ServiceLocator as a pattern/anti-pattern. I've found that there is a trade-off between ServiceLocator as an anti-pattern and Anaemic Domain Model as an anti-pattern - sometimes its just much easier & maintainable to use a service locator.
Use factories instead of accessing the container directly. This keeps your application free from a specific container and prevents the usage of a service locator.
The only situations where you have to access the kernel is once in your composition root and in some very rare situations where you aren't in control of the object creation. In these situations you can still assign the kernel to a singleton object or use the ServiceLocator to make it accessable from anywhere.
ServiceLocator is a static object. Therefore there is no difference from where you are accessing it. I assume that you are accessing the ServiceLocator before it is fully confugured.
Without entering the debate on the use of a service locator, have you tried this NuGet Package CommonServiceLocator.NinjectAdapter?
When I decide I want one, this is what I've used.

Any definitive guide for using Unity with an ASP.NET MVC site that hosts one or more web services?

I'm struggling to find a decent walkthrough for this issue, and was hoping that someone could shed some light on this... I've built an application using a ton of Unity and DI, and I need to pull a few components into a web site and run a WCF service now with them. host a WCF service for clients to connect to it instead of having it included as part of the main application (multi-user scenario where I'm hosting the database for them.)
I've searched and found several documents, but they seem to be focused on running a single service, instead of writing a framework to do the dirty work for me.
I'm wondering, as I've said in the topic, has anyone found "the difinitive guide" on doing this?
Doing a little more research, i did find a few things on how to get the dependency injection to work, where you are implementing/extending an instance provider, a Service Behavior, and a Service Host class... and then in your website, you build a ServiceHostFactory that does the wire-ups from the concrete methods to your interfaces. The only piece of the puzzle I have yet to discover is how you now use *.dlls that have a class which implements IModule, and have the site discover it on the fly.
Discovery on the fly sounds a lot like an extensibility/Add-In scenario. In that case, the Managed Extensibility Framework (MEF) might be a good fit for you.
Despite what many people think, it's also available for .NET 3.5.

Resources