0

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?

1
  • Use nameof(SomeType.TargetProperty) to avoid breakage when refactoring if using the InjectionProperty route. Commented Aug 16, 2018 at 15:16

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Marking as the answer, but still used the constructor based solution. Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.