Managing Modules & Lifetimes

Apr 4, 2008 at 2:19 PM
Edited Apr 4, 2008 at 2:22 PM
Hey,


Say I have a number of modules in my system: Core, ModuleA, ModuleB, etc, where Core contains functionality that's reusable across the other modules. Say for maintainability, ModuleA's DI registration code doesn't care how Core's types are registered with Unity -- just that they, and any types that they depend on, have been/will be registered before any real code is run. So, ModuleA's DI registration doesn't know anything about the lifetimes used by Core.


Consider the following (this is a simple sample so it doesn't show what I mean by independent DI registration):


using Microsoft.Practices.Unity;
 
namespace UnityRepro
{
    class Program
    {
        static void Main(string[] args)
        {
            IUnityContainer unityContainer = new UnityContainer();
 
            unityContainer.RegisterType(typeof(Core.IFoo), typeof(Core.Foo));
            unityContainer.RegisterType(typeof(ModuleA.IBar), typeof(ModuleA.Bar), new ContainerControlledLifetimeManager());
 
            ModuleA.IBar bar = unityContainer.Resolve<ModuleA.IBar>();
            bar = unityContainer.Resolve<ModuleA.IBar>(); //Doesn't hit constructor.
        }
    }
}
 
namespace Core
{
    public interface IFoo
    {
    }
 
    public class Foo : IFoo
    {
    }
}
 
namespace ModuleA
{
    public class IBar
    {
    }
 
    public class Bar : IBar
    {
        private readonly Core.IFoo _foo;
 
        public Bar(Core.IFoo foo)
        {
            _foo = foo;
        }
    }
}


Basically, my concern is that after developing IBar/Bar, you might think that a single instance is possible, but that depends heavily on the implementation of the registered IFoo. You could register IBar/Bar knowing how the currently registered IFoo works, but that's going to end up being a maintenance problem (ie if the registered IFoo is changed, you'd have to update the lifetime of everything using IFoo).


Does Unity have anything in place to help with this?


Thanks