Reputation: 192
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?
Upvotes: 0
Views: 1115
Reputation: 12619
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.
Upvotes: 3