I have a webapplication in development. I'm thinking about using a DecisionTree to analyse certain things.
The DecisionTree has to be created and will be used in different fases. E.g. in a controller something will be compared/checked and a certain view will be returned.
Do I create this DecisionTree at the start of my app and somehow get a reference to it in all my controllers? Or do I recreate it again whenever I use it? I'm guessing the reference method is the best one since a tree gets created on a datatable which consumes memory, etc.. to process
Sounds like a good place for a Singleton.
Might be worth reading up on the Singleton Pattern if you haven't used one before.
http://en.wikipedia.org/wiki/Singleton_pattern
You could initally create the singleton in the Application_Start of Global.aspx if you wanted to, if you want to set some initial state when the Web Application is started.
If you're using som IoC Container (f.e. Ninject) just register this class as singleton and set as dependency for controllers.
f.e.
kernel.Bind<IShogun>().To<Shogun>().InSingletonScope();
object scopes from Ninject documentation
And set it as dependenty in MVC controller, by constructor injection:
MyController(IShogun shogun)
{ ... }
or by property injection:
[Inject]
IShogun { get; set; }
If you're not using IoCC - please start :)
I prefer Ninject but you have quite big choice in IoCCs.
Related
I'm familiar with MVVM Light toolkit's ViewModelBase, Message, but not familiar with the ViewModelLocator. In my application there is Singleton ViewModel, such as PrinterViewModel. Registering is like
SimpleIoc.Default.Register<IPrinter,PrinterViewModel>();
When debugging, the error is something like 'Cannot register: No public constructor found'.
So 2 questions:
Is it bad idea to have Singleton ViewModel?
How to register Singleton ViewModel, since I did not find any overloads to pass an instance for certain interface?
1) As a general rule of thumb, yes. It's the job of the injection framework to set scoping. You might have a database repository class (say) that needs per-form scoping in WPF builds (so the user can cancel the edit), per-request scoping in web builds and singleton scoping in command-line tools. Neither the class itself nor any of its consumers should be aware of what scoping that object has been given.
2) A simple (and not very good) solution would be to just add the singleton instance to your ViewModelLocator and always return that. Another one is to just call GetInstance() without a key and rely on lazy creation. I'm not a huge fan of SimpleIoC though, it's a bit too simple for my liking. Try taking a look at more fully-featured frameworks like Ninject, you'll find they're much more flexible and fluent in their usage e.g.:
Bind<IPrinter>().To<PrinterViewModel>().InSingletonScope();
I had a case where I wanted to register a singleton by myself, because I needed to give an argument to the object constructor.
I then registered the singleton instance by doing:
SimpleIoc.Default.Register<IInterface>(() => new ImplementationClass(param));
The object will be constructed only once, the first time that this line is called:
ServiceLocator.Current.GetInstance<IInterface>();
I have three layers in my solution, Presentation (winforms project), Domain (class lib) and Persistence (class lib).
I am trying to implement dependency injection to decouple them.
My application root is in my presentation layer.
I understand the only time the DI container (unity in this case) should be referenced is in my application root, otherwise I would be simply replacing class dependencies all over the place with a dependency on my DI container (which I suppose is still slightly better).
So with these foundation concepts in mind, I am really struggling with the specific implementation. Perhaps my application root should be in its own seperate project - perhaps a console application. I can then resolve the first 'overallApplication' class, listing IPresentation, IDomain and IPersistence in its constructors. I understand (assuming actual implementations have been registered) the unity framework would then recursively solve all respective sub-dependencies.
In your experience - would you be able to advise if this was a sound approach. I really understand the concept and importance of decoupling, and how this is solved by DI conceptually at a high level, but I am struggling to tie it all together in a real application solution with multiple layers (organised in VS as seperate projects).
Any help or pointers towards examples of proper implementations would be greatly appreciated.
Some thoughts for you in hope that they help.
Throughout your question you make statements such as:
"I really understand the concept and importance of decoupling, and how this is solved by DI..."
The first thing I would evaluate is the understanding that DI != IoC Container (e.g. Unity).
An IoC container is used to remove boilerplate code that results from an existing DI structure. As such I would suggest you refactor without Unity /first/. Then go back and add Unity to reduce your code.
So that:
-1. Make application Di via manual Ctor, Property, Method, Service Locator injection methods.
-2. After this is setup you should see things like:
public View() {
var controller = new Controller(new IView(), new model(), new IService(new Dal(ISession(connectionString))), new , new ILogger(), etc.){}
}
-3. Then once you have something like this in your code you can then use Unity to inject all that fun:
public View() {}
Controller Controller {get;set;} //<- Unity auto builds & populates this for you with all the "new" items normally found in your constructor (or wherever).
While not a production example, it should give an idea of some steps to refactor. Going straight to Unity will put the cart before the horse, so to speak.
I'm currently using Ninject to handle DI on a C#/.Net/MVC application. When I trace the creation of instances of my services, I find that services are called and constructed quite a lot during a the life cycle, so I'm having to instantiate services and cache them, and then check for cached services before instantiating another. The constructors are sometimes quite heavy).
To me this seems ridiculous, as the services do not need unique constructor arguments, so instantiating them once is enough for the entire application scope.
What I've done as a quick alternative (just for proof-of-concept for now to see if it even works) is...
Created a static class (called AppServices) with all my service interfaces as it's properties.
Given this class an Init() method that instantiates a direct implementation of each service interface from my service library. This mimics binding them to a kernel if I was using Ninject (or other DI handler).
E.g.
public static class AppServices(){
public IMyService MyService;
public IMyOtherService MyOtherService;
public Init(){
MyService = new MyLib.MyService();
MyOtherService = new MyLib.MyOtherService();
}
}
On App_Start I call the Init() method to create a list of globally accessible services that are only instantiated once.
From then on, every time I need an instance of a service, I get it from AppServices. This way I don't have to keep constructing new instances that I don't need.
E.g.
var IMyService _myService = AppServices.MyService;
This works fine and I haven't had ANY issues arise yet. My problem is that this seems way too simple. It is only a few lines of code, creating a static class in application scope. Being as it does exactly what I would need Ninject to do, but in (what seems to me for my purposes) a much cleaner and performance-saving way, why do I need Ninject? I mean, these complicated dependency injection handlers are created for a reason right? There must be something wrong with my "simple" interpretation of DI, I just can't see it.
Can any one tell me why creating a global static container for my service instances is a bad idea, and maybe explain exactly what make Ninject (or any other DI handler) so necessary. I understand the concepts of DI so please don't try and explain what makes it so great. I know. I want to know exactly what it does under the hood that is so different to my App_Start method.
Thanks
Your question needs to be divided into two questions:
Is it really wrong to use the singleton pattern instead to inject dependencies?
Why do I need an IoC container?
1)
There are many reasons why you should not use the singleton pattern. Here are some of the major ones:
Testability
Yes you can test with static instances. But you can't test Isolated (FIRST). I have seen projects that searched a long time why tests start failing for no obvious reason until they realized that it is due to tests that were run in a different order. When you had that problem once you will always want your tests to be as isolated as possible. Static values couples tests.
This gets even worse when you also do integration/spec testing additional to unittesting.
Reusability
You can't simply reuse your components in other projects. Other projects will have to use that concept as well even if they might decide to use an IoC container.
Or you can't create another instance of your component with different dependencies. The components dependencies will be hard wired to the instances in your AppServices. You will have to change the components implementation to use different dependencies.
2) Doing DI does not mean that you have to use any IoC container. You can implement your own IDependencyResolver that creates your controllers manually and injects the same instance of your services wherever they are required. IoC containers use some performance but they simplyfy the creation of your object trees. You will have to decide yourself what matters more performance or simpler creation of your controllers.
I am reading StructureMap about dependency injection, well there are two parts first to initialize the mapping, interface to concrete class type, and another one is just instantiation (asking for an instance).
First part requires configuration, setup which is mentioned to be done at a boot strapper.
what s the best practice for a boot strapper? static class with static constructors? how about in IIS?
Also, how can i configure Structure Map so that without restarting the application, I can change the dependencies? is that possible? how?
The configuration is done in the Composition Root. IoC container support for ASP.NET WebForms is very bad. The pages are created by IIS. The only thing you can do here is to inject properties after the page is created.
If you want to do DI for Websites then you should use MVC 3 instead of WebForms. In this case there is an integration package Structuremap.MVC3 that does the bootstrapping for you. You can find it on nuget. https://github.com/webadvanced/Structuremap-MVC3
Using a static class with a static constructor doesn't help much, because the static constructor won't get called until the class is actually used by the running code. Hence your best option is to bootstrap the DI in the program's main() method.
In IIS or similar environment there are usually events that get fired when the application / add-in / component is loaded or 'started'. In ASP.NET (that is in IIS) the global application events in the global.asax.cs file serve this purpose.
I am brand new to IoC and thus have been following the examples provided by Jeffery Palermo in his posts at http://jeffreypalermo.com/blog/the-onion-architecture-part-1/ and in his book hosted here https://github.com/jeffreypalermo/mvc2inaction/tree/master/manuscript/Chapter23
Most important to note is that I am not using a pre-rolled IoC container, mostly because I want to understand all the moving parts.
However, I am creating a windows service rather than an ASP.NET MVC webapp so I am little bogged down on the startup portion. Specifically, in the web.config he registers an IHttpModule implementation INSIDE the infrastructure project as the startup module and then uses a post-build event to copy the necessary dlls into the website directory to get around having a direct dependency in the web project itself.
I don't think I have this type of luxury in a true windows service, so how do I achieve something similar, should I have a small startup project which has dependencies to both the Infrastructure and Core, or is there another method to get around the compile-time restrictions of the windows service?
Thanks in advance.
Based on the tags of this question (c#) I'm assuming that you'll implement the Windows Service by deriving from ServiceBase. If so, the OnStart method will be your Composition Root - this is where you compose the application's object graph. After you've composed the object graph, composition is over and the composed object graph takes over.
In OnStop you can decommission the object graph again.
There's nothing stopping you from implementing the various components of the resolved object graph in separate assemblies. That's what I would do.
I think you missunderstood the role of an IoC framework.
To answer your question
but doesn't the reference imply dependency?
Yes it does, but on an other level. IoC is about dependencies between classes.
Instead of using new Something() in your class you provide a constructor which requires all dependent interfaces. This way the class has no control which implementation is passed to it. This is inversion of control. The IoC Container is just an aid to help managing the dependencies in a nice manner.
Say you have a ICustomerNotificationService interface with an implementation like
public class MailNotificationService : INotificationService
{
IMailerService _mailer;
ICustomerRepository _customerRepo;
IOrderRepository _orderRepo;
public MailNotificationService(IMailerService mailer,
ICustomerRepository customerRepo,
IOrderRepository oderRepo)
{
// set fields...
}
public void Notify(int customerId, int productId)
{
// load customer and order, format mail and send.
}
}
So if your application requests an instance of ICustomerNotificationServcie the container figures out which concrete implementations to take and tries to satisfy all dependencies the requested class has.
The advantage is that you can easily configure all dependencies in your bootstrapping logic and be able to change the behaviour of your application very easily.
For example when testing you start the application with an IMailerService implementation which writes the mails to a file and in production mode a real mail service is wired. This would not be possible if you newed up say a MailerService in your constructor instead of taking it as a parameter.
A good IoC container can handle much more, for you like lifetime management, singletons, scanning assemblies for Types you want to register and many more. We based our entire plugin system on Structure Map for example.
You may want to take a look at this blog article and its second part.