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.
Related
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.
I'm using Ninject 3.0.1.10, MVC 5.0.0, FluentValidation 5.0 and finally FluentValidation MVC plugin library.
I'm trying to configure Ninject so that it injects a service into my AbstractValidator classes. I've read a lot of other answers about how to do this, but none have quite made sense to me. They all mention AssemblyScanner, which I can't find. They also mention accessing the IKernal from App_Start, but in my project App_Start does not have access to the IKernal because it's created inside of a NinjectWebCommon.cs file.
So I'm confused as to how to properly make this happen. Anybody have any clarity on this? Thanks.
You can access the IKernel configured by NinjectWebCommon.cs anywhere in your application. Of course, this usually is not recommended since it's a smell of Service Locator anti-pattern.
But there are cases where we can't escape from it, specially when mixing the frameworks and in your composition root, it's ok.
So, wherever you need, just use:
using Ninject;
//My class that will need access to the IKernel
var kernel = (new Bootstrapper()).Kernel;
The Bootstrapper class is initialized in App_Start.NinjectWebCommon before even the Application_OnStart runs. So it is safe to use even in Global.asax to obtain a reference to the IKernel. It remembers the kernel instance that was provided to it via a static variable inside the Bootstrapper class.
Hope that helps!
I am currently using a library (SuperWebSocket) which is a websocket server library that use a bootstrap which know which instances to load from a configuration file. I have implemented a bootstrap class for this (however the instances arent loaded using IoC). Also the commands from this server are loaded from assemblies reflection. I wanted to use this server in conjonction with my DAL and service layer which use IoC. My main problem is that i can't find a way to put this Console Application (Server) and cooperation with the lib in an IoC scenario without having to end up using the ServiceLocator.
Normally the kernel (Ninject) should be located at the composition root (Look like to be the best practice from many around..) which is rather not possible to do in this case or at least i didn't found how so that why i am here. Also the commands are loaded from assemblies reflection. I could implement a CommandLoader however this is still a problem cause they all inherit from the same interface (Multibinding maybe?). I could make custom interface for each of them but i still can't find a way to load them automatically. Even if i found a way to load them, i still have to be able to get service from attributes which is not easy to do.
Any suggestions ?
If I understand your question correctly then the library is the entry point for all work done. In this situation it depends on the framework what to do. Here are some things you can do the first things are the preferred ones:
Inspect the library and find some way to hook into the framework to intercept the creation of your objects.
Call kernel.Inject(this) after an object is created by the library. Have a look at the Ninject.Web extension. There we added some base classes e.g. NinjectWebPage for WebPage. This new base class calls kernel.Inject after creation. New web pages can now be derived from that base class and use property injection to get dependencies.
Use the ServiceLocator pattern in the objects created by the libray. But just at this level. Anything deeper should use dependency injection.
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.
I'm using AutoMapper in a number of projects within my solution.
These projects may be deployed independantly, across multiple servers.
In the documentation for AutoMapper it says:
If you're using the static Mapper
method, configuration only needs to
happen once per AppDomain. That means
the best place to put the
configuration code is in application
startup, such as the Global.asax file
for ASP.NET applications.
Whilst some of the projects will be ASP.net - most of these are class libraries / windows services.
Where should I be configuring my mappings in this case?
The idea that it should only be required once per AppDomain stays the same, as far as I can tell. I always perform my mappings upon the initialization of the program itself. While I am not using AutoMapper I am using an IoC library (Windsor) which requires a mapping of sorts and this is done from my program.cs file. So when the application loads it performs the mapping and because the resolver is static and in a shared library it is available globally.
I don't know if this answers your question or not, but essentially every app has an entry point and if you need your mappings immediately after entry then the entry is the best place to put them.
I've elected to store my mappings in separate classes for each project so that they are reusable.
protected void Application_Start()
{
RegisterMaps();
}
private void RegisterMaps()
{
WebAutoMapperSettings.Register();
BusinessLogicAutoMapperSettings.Register();
}
This way I can easily call BusinessLogicAutoMapperSettings.Register() if I were to reuse only my BusinessLogic dll in another application or webservice