Autoregistering a concrete type as singleton.

Jun 29, 2011 at 3: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();
                Include(t => t != typeof(BusinessProcess),
                Include(t => t == typeof(BusinessProcess),

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

This doesn't work:

                Include(t => t == typeof(BusinessProcess),

Any idea why?

I'd like to write that or something like:

                Include(t => t == typeof(BusinessProcess),

Jun 29, 2011 at 11:29 PM




 Include(t => t == typeof(BusinessProcess),

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 11: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);