Singleton Per Call Context (Web Request) in Unity

Neat solution, but each instance of LifetimeManager should use a unique key rather than a constant: private string _key = string.Format(“PerCallContextLifeTimeManager_{0}”, Guid.NewGuid()); Otherwise if you have more than one object registered with PerCallContextLifeTimeManager, they’re sharing the same key to access CallContext, and you won’t get your expected object back. Also worth implementing RemoveValue to ensure … Read more

Unity Singleton Code

First, you need a proper lifetime manager the ContainerControlledLifetimeManager is for singletons. For custom initialization, you could probably use InjectionFactory This lets you write any code which initializes the entity. Edit1: this should help public static void Register(IUnityContainer container) { container .RegisterType<IEmail, Email>( new ContainerControlledLifetimeManager(), new InjectionFactory(c => new Email( “To Name”, “[email protected]”))); } and … Read more

Exception is: InvalidOperationException – The current type, is an interface and cannot be constructed. Are you missing a type mapping?

Just for others (like me) who might have faced the above error. The solution in simple terms. You might have missed to register your Interface and class (which implements that inteface) registration in your code. e.g if the error is “The current type, xyznamespace. Imyinterfacename, is an interface and cannot be constructed. Are you missing … Read more

Configure Unity DI for ASP.NET Identity

You also need to resolve the UserManager. The following is an example how you could do it with the UserManager and the RoleManager. In this sample I use the regular Unity 3 package instead of one of the derivates or bootstrappers (had some problems with them in the past). AccountController private readonly UserManager<ApplicationUser> _userManager; private … Read more

How do I use the Decorator Pattern with Unity without explicitly specifying every parameter in the InjectionConstructor

Another approach, thanks to a suggestion from @DarkSquirrel42, is to use an InjectionFactory. The downside is that the code still needs updating every time a new constructor parameter is added to something in the chain. The advantages are much easier to understand code, and only a single registration into the container. Func<IUnityContainer,object> createChain = container … Read more

Can Unity be made to not throw SynchronizationLockException all the time?

I’m sure there’s a lot of ways code could call SynchronizedLifetimeManager, or a descendant like ContainerControlledLifetimeManager, but there were two scenarios in particular that were causing me problems. The first was my own fault – I was using constructor injection to supply a reference to the container, and in that constructor I was also adding … Read more