2

In my code, I'm often finding myself setting up classes which utilize constructor-based dependency injection and have a number of dependencies coming in. It's not uncommon for me to end up with something like:

public class MyClass
{
    private readonly IMyDependency1 _dependency1;
    private readonly IMyDependency2 _dependency2;

    public MyClass(IMyDependency1 dependency1, IMyDependency2 dependency2)
    {
        _dependency1 = dependency1;
        _dependency2 = dependency2;
    }
}

This, while obviously necessary from a functionality perspective, feels like needless boilerplate. I've used libraries in other languages such as Java which help with this by offering annotations/attributes to handle the bindings for you. What I'm looking for is something that handles this in C# (preferably compatible with .net core), something like this:

public class MyClass
{
    [FromConstructor]
    private readonly IMyDependency1 _dependency1;

    [FromConstructor]
    private readonly IMyDependency2 _dependency2;

    public MyClass(IMyDependency1 dependency1, IMyDependency2 dependency2)
    {
        //whatever Bind() call required here
    }
}

Bonus points if the presence of the annotation can result in the package autogenerating the required constructor meaning I can avoid needing to write a constructor at all in the case where all the constructor is doing is handling dependency binding.

Does anything like this exist?

VMAtm
  • 27,943
  • 17
  • 79
  • 125
Josh Kitchens
  • 1,080
  • 11
  • 18
  • See [here](https://stackoverflow.com/questions/38459625/property-injection-in-asp-net-core), the answer is no and this question also gives some reasons why not.... – Matt Jun 01 '17 at 15:57

1 Answers1

0

I'm not aware of any library which provides such functionality out of the box, but you try write one by your self, with small addition of AOP library named PostSharp.

Basic idea is this: apply an PostSharp attribute aspect to a given properties, get the DeclaringType information, and create a constructor on fly and emit it to your library. You can even create binding for your IoC container at the same time. Here is a question on SO about applying the aspects on types in PostSharp.

The downsides of such a solution are that PostSharp Architecture packet isn't free, PostSharp do it's work after compile, so it basically partially overwrites your library, and I'm not sure would you be able to emit constructor to your existing library or you need to create a separate one. Also .Net Core version of PostSharp is in experimental phase.

VMAtm
  • 27,943
  • 17
  • 79
  • 125