Autoregistering a concrete type as singleton.

Jun 29, 2011 at 2:51 PM

I have a concrete type called BusinessProcess that I want to register as a singleton, while reregistration is going on. It doesn't implement any interfaces, but it does depend on some in the constructor.

This works if I code:

            UnityContainer container = new UnityContainer();
            container.ConfigureAutoRegistration().
                Include(t => t != typeof(BusinessProcess),
                    Then.Register().AsAllInterfacesOfType()).
                Include(t => t == typeof(BusinessProcess),
                    Then.Register().As<BusinessProcess>().UsingSingletonMode()).
                ExcludeSystemAssemblies().
                ApplyAutoRegistration();

But it doesn't scale very well to more singletons.

This doesn't work:

                Include(t => t == typeof(BusinessProcess),
                    Then.Register().UsingSingletonMode()).

Any idea why?

I'd like to write that or something like:

                Include(t => t == typeof(BusinessProcess),
                    Then.Register().AsSelf().UsingSingletonMode()).

Coordinator
Jun 29, 2011 at 10:29 PM

 

This:

 

 Include(t => t == typeof(BusinessProcess),
                    Then.Register().UsingSingletonMode())

doesn't work because default registration options (when using just Then.Register()) is to register type as all of its interfaces. In your case I'm guessing BusinessProcess doesn't implement any.

This should do the trick (you can also create AsSelf extension method that would just be As(t => t) or use As(t => ...) for any custom registrations where by providing lambda you make a decision how to register certain types based on the actual type):

Include(t => t == typeof(BusinessProcess),
                    Then.Register().As(t => t).UsingSingletonMode()).

Jun 30, 2011 at 10:28 AM

Yep, BusinessProcess has no interfaces.

That works, thanks. I made the extension method as follows:

namespace UnityExtensions
{
    using Unity.AutoRegistration;

    public static class UnityRegistrationExtensions
    {
        /// <summary>
        /// Register a type as itself (as opposed to its interfaces)
        /// </summary>
        /// <param name="registration"></param>
        /// <returns></returns>
        public static IFluentRegistration AsSelf(this IFluentRegistration registration)
        {
            return registration.As(t => t);
        }
    }
}