Unity Singleton Code

ぃ、小莉子 提交于 2019-11-27 13:56:36
Wiktor Zychla

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", 
            "to@email.com")));
}

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   
   [Dependency]
   public IEmail _email { get; set;}

}

and then

OperationEntity entity = somehowdeserializeit;

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

You could use:

container.RegisterType<IEmail, Email>(new ContainerControlledLifetimeManager());

If IEmail is a singleton with no dependencies (just custom arguments), you can new it up yourself:

container.RegisterInstance<IEmail>(new Email("To Name", "to@email.com"));

That will register the supplied instance as a singleton for the container.

Then you just resolve the service:

container.Resolve<OperationEntity>();

And because you are resolving a concrete type, there is no registration required. Nevertheless, if you would like that service to also be a singleton, you can register it using ContainerControlledLifetimeManager and then all calls to resolve (or when injecting it as a dependency to another class) will return the same instance:

container.RegisterType<OperationEntity>(new ContainerControlledLifetimeManager());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!