简体   繁体   中英

Auto-setting property values with Unity dependency injection

I have a context interface with a few properties that I would like unity to auto-set when the interface is resolved. Here is the interface and class.

public interface IAdapterContext
{
    IFoo Foo { get; }

    IBar Bar { get; }
}

public class AdapterContext
{
    public IFoo Foo { get; set; } 

    public IBar Bar { get; set; }
}

The interface resolves to the class successfully, but all of the instance members are null. The corresponding instance member interfaces are registered.

One solution is to add a constructor in the class that receives all of the values, but I would rather not do this since I also want the default constructor for ease of testing. Having both a default and a non-default just to satisfy unity doesn't sit well with me.

Another solution is to use the InjectionProperty class, but this overall a more complex solution than just adding a constructor. It also decouples the property names from the actual class, which could break during refactoring.

Does unity support auto-setting property values for an implemented interface, or does it always need to be done through the constructor/InjectionProperty?

There is a Dependency attribute that you can use to mark properties that you want to inject.

public class AdapterContext
{
    [Dependency]
    public IFoo Foo { get; set; } 

    [Dependency]
    public IBar Bar { get; set; }
}

I would not recommend this solution. I always go with constructor injection and configure dedicated container for test that contains mocks of dependencies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM