IoC

Autofac: resolve dependencies later in code & pass your parameters

March 22, 2012 .NET, Autofac, C#, IoC 3 comments

Today I played a bit with Autofac, and I learned few simple but nice tricks. This blog post is for my personal notes. If you haven’t used Autofac or know little about IoC it might be of interest for you.
Below we have fun setup. I call it “fun”, because it is very explicit and easy to understand. Reading though it makes it clear what dependencies are:
builder
    .Register(b => new F())
    .As<IF>();

builder
    .Register(b => new E())
    .As<IE>();

builder
    .Register(b => new D1())
    .Named<ID>(SomeD1Name);

builder
    .Register(b => new D2())
    .Named<ID>(SomeD2Name);

builder
    .Register((b,prms) => new C(b.Resolve<IE>(), prms.TypedAs<IF>()))
    .Named<IC>(CName);

builder
    .Register((b,prms) => new B(b.Resolve<IF>(), b.ResolveNamed<IC>(CName, prms)))
    .As<IB>();

builder
    .Register(b => new A(b.Resolve<IE>(), 
        b.ResolveNamed<ID>(SomeD1Name),
        b.ResolveNamed<ID>(SomeD2Name)))
    .As<IA>(AName);

builder
    .Register(b => new Service(b.Resolve<IComponentContext>(),
        b.Resolve<IA>(), b.Resolve<IB>()))
    .As<IService>();

And that’s it.

I would like to pay your attention to few things. One of them is “prms.TypedAs”, which is great way to inject parameters for your construction later on. Another thing is passing IComponentContext to the Service instance. This two things altogether will allow you to resolve dependencies inside of your Service class, just like below (assuming you have field _componentContext):
_componentContext.Resolve<IB>(new TypedParameter(typeof(IF), new F1()));

As you understood this will create us instance of B, by passing into its constructor instance of F and instance of C, created basing on E and another implementation of IF, which is F1 (not one registered at very beginning). Isn’t it nice?
For serious reading on Autofac please refer to its web site:


3 comments


Inversion Of Control and Dependency Injection

October 21, 2009 IoC 7 comments

At first I would like mention that I’m not first who writes such article, but I find this to be very interesting. I will start with describing of Inversion Of Control in theory starting from easy, then I will move to usage of StructureMap.

I interacted with Inversion Of Control Containers aka StructureMap when I even haven’t understanding what is it and why is it needed. I got few UT failures, saying that something is wrong with IoC setup. And I spent a lot of time figuring out what is that bootstrap class doing. So this was my first interaction. Then I decided to prepare Developers Meeting on this theme.

Inversion of Control and Dependency Injection

We will start with example which is very similar to Martin Fowler’s (http://martinfowler.com/articles/injection.html) and then will move to StructureMap using. So let us imagine that we have class MusicPlayer, which has method GetBandSongs. That method will work with SongFinder to get all songs and then will filter out songs which are created by some particular band.

public class MusicPlayer
{
    private SongFinder songFinder;
    public MusicPlayer()
    {
        songFinder = new SongFinder();
    }
    public Song[] GetBandSongs(String band)
    {
        var allsongs = songFinder.FindAllSongs();
        return allsongs.Where(x => x.Band == band).ToArray();
    }
}

As we see Music Player is coupled to SongFinder and this is not good thing. Why? At first because of extensibility issue. If SongFinder will need to use plain text file instead of XML we will need rewrite body of SongFinder, at second testability is low because we cannot pass songs into PlayBandSongs method to test it, and at third reusability is also low because logic is too generic…
Let us do some refactoring with introducing interface for SongFinder, let us call it ISongFinder.

public interface ISongFinder
{
    Song[] FindAllSongs();
}

Now we will have MusicPlayer with member of this interface type. So this allows us work with different sources of data. i.e. logic no longer depend on concrete realization.

private ISongFinder songFinder;
public MusicPlayer()
{
    songFinder = new  SongFinder();
}

But the Music Player is still coupled to concrete realization of finder. Current design looks like:

I do think that you want to say “Hey, put finder into player constructor!”, and you are very right here. This is one of ways how to inject dependency here. And this is pure good idea, but there are other ones which leads us to something which will give possibility to inverse controlling.
Ok, let us create factory which will create for us instances of ISongFinder. See:

public class SongFinderFactory
{
   public ISongFinder GiveUsDatabaseSongFinder()
   {
      return  new SongFinder();
   }
}
public  MusicPlayer()
{
   songFinder =  SongFinderFactory.GiveUsDatabaseSongFinder();
}

And the UML:

Now we have Player decoupled from SongFinder, because creation is redirected to Factory.
Another way to have decoupled code is to introduce here Service Locator. Using Service Locator we can register couple of services and then use one of the registered somewhere we need. So we have some code which registers services we will use, let call it Assembler, and we have code where we are using particular services. Easy! See:

///
/// Using Service Locator we can register services for our application.This should be one storage,
/// so we make methods static
///
public static class ServiceLocator
{
    private static Dictionary m_services = new Dictionary();
    public static void RegisterService(Type type, Object implementation)
    {
        m_services.Add(type, implementation);
    }
    public static Object GetService(Type type)
    {
       if(m_services.ContainsKey(type))
       {
          return m_services[type];
       }
       return null;
    }
}
// Services Registering code
// It decoupled to ISongFinder, SongFinder and to ServiceLocator,
// but this is Assembler code, and that is good
static void RegisterServicesNeeded()
{
   ServiceLocator.RegisterService(typeof(ISongFinder), new SongFinder());
   //register another services as needed
}

Let us now take a look at constructor of MusicPlayer:

public  MusicPlayer()
{
   var fiderService =  ServiceLocator.GetService(typeof (ISongFinder));
   songFinder =  (ISongFinder)fiderService;
}

And the design with ServiceLocator will look like here:

Now we got testable, reusable and extensible code. Looks very fine, but doesn’t it look difficult? Could be, because after we got decoupling of MusicPlayer and SongFinder we also got sequence dependence, our service depends on infrastructure code and we need to do cumbersome setup in tests. Actually that is correct, but system with possibility to setup Dependencies somewhere in one place is much better. That is not all. This times we have lot of IoC containers, so they allow us to configure dependency via config file or either through reflection in code during run-time!
We continue with adding to our project one of the IoC containers – StructureMap. (http://structuremap.sourceforge.net/Default.htm) With this we will no longer need our own Service Locator. So now we can setup dependencies in some Bootstrap once, but this is not static dependencies setup – we can use different implementations for different scenarios.
Let us refactor MusicPlayer with StructureMap. Registration code will look like:

ObjectFactory.Initialize(x =>x.ForRequestedType<ISongFinder>).TheDefaultIsConcreteType<SongFinder>());

And MusicPlayer constructor will be like:

public MusicPlayer()
{
     songFinder = ObjectFactory<ISongFinder>.GetInstance();
}

So, with these two lines of code we replaced functionality of ServiceLocator. Ok let us imagine that we have Constructor dependency:

public MusicPlayer(ISongFinder sngFinder)
{
     songFinder = sngFinder;
}

Now we can setup dependencies like here:

ObjectFactory.Initialize(x =>
{
    x.ForRequestedType<MusicPlayer>().TheDefaultIsConcreteType<MusicPlayer>();


    x.ForRequestedType<ISongFinder>().TheDefaultIsConcreteType<SongFinder>();


});

And get instance of MusicPlayer by ObjectFactory. And this is quite amazing thing here, because our IoC Container built dependencies tree and did all required initialization.

var musicPlayer = ObjectFactory<MusicPlayer>.GetInstance();

In real world applications we could have framework built on interfaces and we could have couple of the pluggable assemblies which goes with IoC configuration, so IoC Containers make difference between framework and library.


7 comments