1

I'm working on a ASP.net core app and of course using dependency injection. Mainly injecting required services in constructors of pages or other services. Some of these injected services are the same in almost every other constructor. For example there is the ILogger<T>, an IAppInfo holding some application wide information and there is an IFileServices used in many other services also. So I end up with lots of injections in constructors, in some more than 7. Question is, which is the best way to get rid of all there parameters used in almost every constructor?

For now I have implemented another service with methods to get the required services:

    public interface IBasicsService<out T>
    {
        ILogger<T> GetLogger();
        ApplicationInfo GetApplicationInfo();
    }

implemented in:

    public class BasicsService<T> : IBasicsService<T>
    {
        private readonly ILogger<T> _logger;
        private readonly ApplicationInfo _info;

        // ReSharper disable once ContextualLoggerProblem
        public BasicsService(ApplicationInfo info, ILogger<T> logger) {
            _info = info;
            _logger = logger;
        }

        public ILogger<T> GetLogger() {
            return _logger;
        }

        public ApplicationInfo GetApplicationInfo() {
            return _info;
        }
    }

Is that correct? Is it better to inject IServiceProvider and resolve services with this? Thank you.

dseferlis
  • 467
  • 2
  • 6
  • 11

1 Answers1

1

It is better not to use IServiceProvider it hides the dependency of your service Assume that in some case you want to test this service oops your are forced to Mock IserviceProvider. The task that you wants to do has no differ from using ServiceLocator This link can help you to see why it is not good to use ServiceLocator

ServiceLocator is an antipattern

But if you are really wants to do that in any circumstances, Constructor injection is not the only way that you can use to inject dependency. There is another way that called Property injection This is a good discussion about property injection

Property Injection in ASP.NET Core

Do not forget you can configure asp.net core to use some other IOC containers like castle Windsor or Unity that support property injection