0

Assuming the classes have the following structure for the purpose of recycling useful code:

public abstract class BaseWriter {...}

public class CommonWriter : BaseWriter {...}
public class CustomWriter : CommonWriter {...}

we have also another class that instantiates these writers, however these being initialized by dependency injection:

public class RawReports {
   public CommonWriter Common {get; set;}
   public CustomWriter Custom {get; set;}
}

I had a problem, injecting like below because all instances of BaseWriter were initialized with CommonWriter implementation:

services.DeclareServicesFor<CommonWriter>();
services.DeclareServicesFor<CustomWriter>();

How do i solve it and keep using dependency injection?

3
  • 2
    There's no DeclareServicesFor in .NET and googling doesn't return any .NET-related results. What DI library are you using? Is this your own custom method? Commented Jan 28 at 11:44
  • 1
    It is generally recommended to use composition rather than inheritance for recycling useful code. So the main idea seem questionable, and it is not at all clear what DI framework you are using, or the overall goal.
    – JonasH
    Commented Jan 28 at 11:53
  • DeclareServicesFor is from Castle.Windsor Commented Apr 17 at 21:10

1 Answer 1

0

Later in the day, I saw that I could solve this by defining the superclass as default implementation, and the subclass would be instantiated when necessary:

services.DeclareService(null, 
                       [typeof(CommonWriter)],
                        DeclarationPolicies.IsDefaultImplementation);
services.DeclareServicesFor<CustomWriter>()

the CommonWriter probably overrun all implementations because it was the first to be registered.

1
  • 2
    There's no DeclareServicesFor or DeclarationPolicies in .NET's Microsoft.Extensions.DependencyInjection and registering multiple types for the same base type allows you to retrieve all of them as an IEnumerable<BaseType>. Is this your own custom DI? Or helper methods wrapping Microsoft.Extensions.DependencyInjection? Commented Jan 28 at 11:46

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.