YairHalberstadt / stronginject

compile time dependency injection for .NET
MIT License
845 stars 24 forks source link

Support init-accessor of properties #113

Open Yeah69 opened 3 years ago

Yeah69 commented 3 years ago

Hi, I think it would be awesome if the C# 9.0 init-accessors for properties would be supported. Consider following example:

    public interface IRunnable
    {
        void Run();
    }

    internal class Runnable : IRunnable
    {
        internal IHelloWorldPrinter HelloWorldPrinter { private get; init; }

        public void Run() => HelloWorldPrinter.DoIt();
    }

    public interface IHelloWorldPrinter
    {
        void DoIt() => Console.WriteLine("Hello World!");
    }

    internal class HelloWorldPrinter : IHelloWorldPrinter
    {
    }

Without the init-accessor feature I would prefer construtor injection over property injection, because for the latter the property would need to become mutable. In my opinion the init-accessor is changing the game. In the example above, if constructor-injected, then the constructor would initialize a readonly field or get-only property anyway. So by supporting init-accessor the dependency could be injected into the "get-only" (of course there is also the init) property right away.

Additionally, that way the dependencies which are not relevant for the constructor but later on could be separated from the constructor.

One little caveat is of course that the init-injected properties cannot be used in the constructor, because they'll be initialized by the runtime after the constructor run through.

YairHalberstadt commented 3 years ago

In the future CSharp plans to support required properties. https://github.com/dotnet/csharplang/issues/3630

Init properties can only be set at construction, but don't have to be set. Required properties have to be set at construction.

As such I think it makes more sense to wait for required properties and support them, than to support init properties.

We could view init properties as optional dependencies, i.e. - if we have something that can provide it then use that, otherwise ignore it, but I'm not sure if that would be best for users or not.

Yeah69 commented 3 years ago

Didn't know about this proposal. Considering that, you are right the required properties would be a better fit for what I suggested.