Ioc container placement within enterprise application - visual-studio

I've been looking into Ioc containers and AOP recently, and I'm pretty amazed by the concepts. I'm struggling however to decide how and where to implement the container.
The articles below suggest implementing the container in the 'application entry point':
Best Practices for IOC Container
IOC across visual studio projects?
Not understanding where to create IoC Containers in system architecture
Now - my thought-experiment application will consist of multiple visual studio projects ( one for data access, winforms application ). And let's say I want to use AOP for logging with Log4net, and so I setup log4net in the Ioc container.
So WinForms application in entry point, that's where Ioc container should go.
Here's the question: if I want to log stuff in my data access project/layer, should I add a
reference to my winforms application, get the ioc container from there, get the log4net instance out of it and use it for logging?
That would mean my data-layer depends on winforms application, that can't be right. How about I put the container is something like a 'Common' project within the solution. That way, all related projects (Data access/winformsa etc.) can access the container.
What is the right way to go here?

Your application's Composition Root would be the Windows Forms project. This is the only project which should have a reference to a DI Container.
In all other projects, dependencies should be injected via Constructor Injection. All decent DI Containers understand this pattern and use it to Auto-wire dependencies from the Composition Root.

I've abstracted my container into a separate assembly that all other assemblies / projects depending on its services reference. The container project has just a single class and - more or less - a single method:
public class MySpecialContainer
{
public T Resolve<T>() { // ... Get stuff from the IoC container }
}
The container build would either occur in MySpecialContainer's ctor or just add another method like Initialize() or some such.
The only problem is this approach broke down for me when I used Autofac and had both a Windows Service and ASP.Net project needing the container. Each had its specific requirement for scoped-lifetime services: Windows Service - PerLifetimeScope, ASP.Net - PerHttpRequest. I guess I could've passed in an argument into MySpecialContainer that denoted which scenario to configure for but I decided just to take on an Autofac dependency directly.
The good news is, if you stick to ctor injection, then you can very easily swap out various container implementations - Autofec, Ninject, StructureMap, etc.

Related

nested reference can be accessible from dotnet core 1

I have created Business and DataAccess Layer for my web project using dotnet core.
I have added Data access reference in Business layer and referenced the business layer in UI (web project) layer.
I seen, I am able to access my Data access layer from my UI (web) project. I am really wondering, It can lead to violation of any application design.
Appreciate help, if anybody come across this and how to restrict access to data access layer from UI.
Yes, an indirect dependency is a dependency too.
And your toplevel (MVC) project has to reference everything, direct or indirect, in order to get all modules loaded. And to set up the dependency injection.
You can get better separation by introducing an interfaces layer in a separate project. For example IBusinessClass and IDataAccessClass.
That works for everything but the main project so if you want this particular separation from your example, move your Controllers to a separate project and depend that on the IBusiness interfaces only. Though I'm not sure how that works with MVC's conventions.

OSGI service vs. Singleton?

I am a beginner to OSGI and I am wondering if someone can enlighten me about the difference between creating OSGI service vs singleton pattern. For example, suppose I have a bundle core which provides IService, and multiple bundles that needs to access this. I can:
register a service in the core-bundle, in which the plugins can access
provide a singleton class, which provides the service
Using OSGI service seems to be quite cumbersome; and since the plugins have to depend on Core anyways (to get the interface), what's the advantage of using OSGI service?
Services are the connections between independent modules. Having modules depend on services (with their specification packages) can significantly reduce coupling between modules and thus provide much of the benefits of modularity.
I think the singleton pattern is used in two different ways: you just want a single object be shared between a set of users (e.g. a Log Service) or you can really only have one instance (e.g. there is only one piece of hardware). In general, I see that most people in the enterprise software world talk about the former. However, experience shows that when projects grow, singletons become less singleton but more a shared object, or at least an appearing to be shared object.
The nice thing in OSGi is that you can model both and the clients of the "singleton" are oblivious of it, nor does it require some central configuration. The reason is that OSGi relies on modules in charge, registering a service is a local decision as is listening to a service.
The power of services are not in its dynamics (they are cool though, especially during development), the essence of service is that they provide full local control inside the module without central configuration. Once you understand how powerful this is, there is no way back :-)
Last, OSGi services are not cumbersome, not since we have DS with annotations. Registering a service is now much simpler than creating a Spring bean, no xml, no central configuration:
// A component registered as a ISingleton service
#Component
public class MyImpl implements ISingleton {
void doSingle() { ... }
}
// A component that uses the ISingleton component
#Component
public class MyConsumer {
#Reference
void setISingleton(ISingleton is) { ... }
}
... And the dynamics come largely for free ...
Short answer: if you don't -- and won't -- need the benefit of an OSGi service (e.g., dynamically-managed service implementations and service searches), then you don't need an OSGi service.
But there is more to consider here than whether or not the service would be cumbersome. Heck, OSGi itself can be considered cumbersome. Will another bundle need to provide an implementation of that class? Maybe not. Will the Core bundle ever shut down or otherwise be unable to provide an implementation on demand? Maybe.
To determine if a service is right for the class in question, read the run-down of the specific benefits of a service on the OSGi Alliance's What Is OSGi page. They have a very good explanation of how your singleton class may become more cumbersome than a service.
Good luck.
My OSGi Threading Model 's poc is resulted into believing me that, every service is a singleton for a service consumer. As the only one service object get registered into the osgi service registry. (but you can override this behavior also). So as far as programming is considered, the behavior of a singleton class and an OSGi service is the same. Your class level variables are shared among the various service consumer calls.
I will say OSGI Service is Singleton++
But there are also differences.
OSGi gives you a separate class-loader for each service which is not possible in a singleton. All {singleton} classes are loaded by a single classloader. We can't have two classes with the same name (fully qualified name) in a singleton but this is possible in OSGi.
In certain situations we must be confirmed that a class should be loaded only once (making hibernate session factory, hdfc service initialization, POJO creations which are heavy initializations required only once). Now if you are living in a Java EE scenario some times your singleton class gets loaded twice by two different classloaders. So this results into two times the execution of a static block; an unnecessary job.
Such classloader problems are easily handled by OSGi (as you are a beginner I feel classloading itself is a problem for you in the next few days).
Another great feature provided by OSGi is updating a bundle.
Consider you changed the code in your singleton class. Now you need to deploy this updated class in your running application. You essentially need to restart the system, so that every singleton class loader updates the new instance of the singleton. This is not required in OSGi, just update the bundle.
I will say if you're going to design for larger applications (enterprise scale), or if you need to design code for a limited hardware capacity (low memory constraints, low computing power) then go for OSGi, it is best for the extreme ends. For all others your normal java coding will work perfectly.
You can manage the life cycle (deploy new version of the service, concurrently run multiple versions etc) of a service but you can't manage the life cycle of singleton without restarting the JVM (even with restart you can just have 1 version available at any point of time).

How to dynamically manage project dependancies

We are writing a new set of services and have decided to make them share a common interface... calling it a BaseService. The idea is that whenever anyone wants to develop a new service in our organization, they should be just able to extend and use this BaseService.
We have written a few other classes which also form a part of this base jar, it does things like handle transactions and connect to database using hibernate etc.
Right now all the services that extend the BaseService are a part of the same project (Eclipse + Maven), and some of the services are dependent on each other, but because they are in the same project we don't have a problem with dependencies.However, we expect 40-50 services to be written which would extend base service and would also be interdependent.
I am worried that the size of the base project would be huge and that just because when someone has to use one service they might have to depend on my base jar which has 50 services.
Is there a way that we can make some projects dynamically dependent on others?
Lets say I have a service A which depends on service B, when I build/compile Service A,it should be able to realize that it has a dependency on service B and automatically use the Service B jar.
I have heard of OSGi, will it solve my problem or is there a way I can do it with Maven or is there a simpler solution ?
Sorry about the long post !
Thanks in advance for your suggestions
It doesn't make any sense to "dynamically" manage project dependencies, since build dependencies are by definition not dynamic.
Your question, at least for the moment, seems to be entirely about how to build your code rather than about how to run it. If you are interested in creating a runtime system in which new service implementations can be dynamically added then OSGi may be the solution to look at. An extra advantage here would be that you could enforce the separation of API from implementation, and prevent the implementing services from invalidly depending on parts of your core module that you do not want them to have visibility of.
You could also use OSGi to manage evolution of your core service API through versioning; for example how do you communicate the fact that a non-breaking change has been made to the API versus a breaking change etc.
I would say there are two options depending if i understand your question correct. First one. You have already defined an interface (java term) and now you have different implementations of that. The simple solution for Maven would be to a have a module which is called for example: service-api and than this will be released and can be used by others as dependencies. On their side they simply implement the interface. No problem with the dependencies. If you are more talking about OSGi than you should take a look to maven-tycho.

Two Autofac containers competing in a single webrequest

A bit of a strange situation: I'm developing an ASP.NET MVC 3 application that uses Autofac as its IoC container and that can be dropped into any existing MVC or WebForms application.
Everything works fine, except when the other application also uses Autofac. I've created a custom DependencyResolver wrapper that combines my application's AutofacDependencyResolver with DependencyReolver.Current of the other application (when set). Resolving of components just fails sometimes although I can see in the debugger that everything is properly registered.
I suspect that both inner resolvers are competing for a spot in the HttpContext.Items collection, but I can't get my finger behind the exact issue.
What would be the proper way to handle this situation?
You could isolate the configuration into a module. When you integrate one application into the other, register the module.

why a ioc framework for MVC 3?

After plenty of reading, I still don't understand Unity for MVC 3.
Specific points
Why use it? I can create a controller that in its constructor, it takes a new EF context for testing.
How? I keep seeing bits are parts, but is there an end to end walk through on implementing Unity on MVC 3 (Live)? There seem to be plenty on Beta and RC, but the code always seems to have a problem on live frameworks.
Currently this is not impacting my unit testing, since my controllers have overloaded constructors, as does my EF context.
If you have a small project, you may not benefit from IoC.
Lifetime management if a plus for me. I don't have to dispose a repository (or service layer) in every controller. It thins out my code and creates the object for me. In addition, I know I have a clean separation in case I ever need to change things. It almost forces me to. I use for example IRepository that is backed by entity framework. For testing I use a fake IRepository implementation. So sure, I could manually create it in my application but this leads to some bad practices in larger projects and I lose the benefits of having the interface.
I have a basic demo for a super short talk I did recently on this for (15 minutes) mvc and unity for dependency injection using the unity.mvc3 nuget package:
http://completedevelopment.blogspot.com/2011/12/using-dependency-injection-with-mvc.html
Btw. Dependency Injection in .Net - best book on the subject without a doubt.
It's very useful for wiring up all your dependencies, handling life cycle of your objects, error handling, transaction handling, testing purposes and ...
All of above point are advantages of using an IoC framework, but I strongly recommend using Ninject. it has a very friendly DSL for binding modules, has out of box library and extensions for ASP.NET MVC and is an open source lightweight DI framework.
It has also many extensions.

Resources