Unity Singleton Code

后端 未结 4 1915
逝去的感伤
逝去的感伤 2020-12-03 04:48

I\'m new to Unity and am trying to write some Unity logic which initialises and register/resolves a singleton instance of the Email object so that it can be used across seve

相关标签:
4条回答
  • 2020-12-03 05:06

    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());
    
    0 讨论(0)
  • 2020-12-03 05:13

    You can, for example, use this code:

    public class example : MonoBehaviour
    {
        public static example instance;
    
        public void Start()
        {
            (!instance)
                instance = this;
        }
    }
    
    0 讨论(0)
  • 2020-12-03 05:17

    You could use:

    container.RegisterType<IEmail, Email>(new ContainerControlledLifetimeManager());
    
    0 讨论(0)
  • 2020-12-03 05:20

    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 );
    
    0 讨论(0)
提交回复
热议问题