Unity - Inject different classes for the same interface

后端 未结 3 951
野性不改
野性不改 2021-02-04 07:03

I have one interface: IFoo
Two classes implementing that interface: FooOne and FooTwo
And two classes ClassOne and

3条回答
  •  萌比男神i
    2021-02-04 07:58

    You need to give them registration names to do this:

    // Create an instance of a service you want to use. Alternatively, this
    // may have been created by another process and passed to your application
    LoggingService myLoggingService = new LoggingService();
    
    // Register the existing object instance with the container
    container.RegisterInstance("Logging", myLoggingService);
    
    // Register a mapping for another service your application will use
    container.RegisterType("DataService");
    
    // When required, retrieve an instance of these services
    IMyService theDataService = container.Resolve("DataService");
    IMyService theLoggingService = container.Resolve("Logging");
    

    Taken from Resolving Instances Of Types Using Unity

提交回复
热议问题