1

I have the child-parent class relationship but I don’t have any startup class to resolve the dependency explicitly. In addition, I don't want to remove empty constructor from child class as it has a dependency. How and Where can I configure my containers to achieve dependency injection implementation?

Currently, I am achieving it using below logic for unit testing mocking purpose.

Is it possible to dynamically resolve dependency using MEF C# or through base lass. Any help appreciated.

e.g.

 public class child : Parent
 {
       private ILogger _logger;
       public child() : this(new FileLogger()) { }

       public child(ILogger logger)
       {
            _logger = logger;
       }

       public void DoWork()
       {
             //Perform Work.
             _logger.Log("Log Work Here");
       }
 }

public abstract class Parent
{
        //Common Operations
}

public interface ILogger
{
        void Log(string message);
}

//Multiple Inplementation for ILogger
public class FileLogger : ILogger
{
      public void Log(string message)
      {
            //Log into file.
      }
}
Sumit Deshpande
  • 2,155
  • 2
  • 20
  • 36
  • try register your dependencies to main method – programtreasures Apr 03 '18 at 05:02
  • Any examples on this? – Sumit Deshpande Apr 03 '18 at 05:14
  • If you are using .net core than I guess you must need to add startup class to web builder to configure services. – programtreasures Apr 03 '18 at 05:19
  • 1
    What do you mean by "I don’t have any startup class to resolve the dependency explicitly"? Every application has a start-up location where the first code runs. This is the place where you would wire up your dependencies. This location is called the [Composition Root](http://freecontent.manning.com/dependency-injection-in-net-2nd-edition-understanding-the-composition-root/). – Steven Apr 03 '18 at 08:37
  • I have the similar implementation like aws lambda where I don't have startup class - E.g. https://stackoverflow.com/questions/46984918/aws-lambda-environment-variables-and-dependency-injection – Sumit Deshpande Apr 03 '18 at 08:54

0 Answers0