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)
        .RegisterType<IEmail, Email>(
        new ContainerControlledLifetimeManager(),
        new InjectionFactory(c => new Email(
            "To Name", 
            "[email protected]")));

and then

var opEntity = container.Resolve<OperationEntity>();

Edit2: To support serialization, you’d have to rebuild dependencies after you deserialize:

public class OperationEntity
   // make it public and mark as dependency   
   public IEmail _email { get; set;}


and then

OperationEntity entity = somehowdeserializeit;

// let unity rebuild your dependencies
container.BuildUp( entity );

Leave a Comment