Search code examples
c#unity-containercastle-windsor

Converting CastleWindsor-code to Unity-code


I used the write the following in Windsor Castle :

public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        //Makes sure we only get one DbConnection
        container.Register(Component.For<IMyMusicSession>().UsingFactoryMethod(_ => new MyMusicSession("MyMusicDb")).LifestylePerWebRequest());
    }

How can I do the same in MS Unity? I'm new to Unity, so that's why I ask the question. The "MyMusicDb" is actually the name of the connectionstring as written in the web.config.


Solution

  • Here is how you can do it:

    var container = new UnityContainer();
    
    container.RegisterType<IMyMusicSession>(
        new PerRequestLifetimeManager(),
        new InjectionFactory(c => new MyMusicSession("MyMusicDb")));
    

    Be sure to install the Unity.Mvc NuGet package.