Dependency Injection in .NET with examples?

前端 未结 8 1498
别跟我提以往
别跟我提以往 2020-11-27 14:31

Can someone explain dependency injection with a basic .NET example and provide a few links to .NET resources to extend on

8条回答
  •  独厮守ぢ
    2020-11-27 15:25

    Here's a common example. You need to log in your application. But, at design time, you're not sure if the client wants to log to a database, files, or the event log.

    So, you want to use DI to defer that choice to one that can be configured by the client.

    This is some pseudocode (roughly based on Unity):

    You create a logging interface:

    public interface ILog
    {
      void Log(string text);
    }
    

    then use this interface in your classes

    public class SomeClass
    {
      [Dependency]
      public ILog Log {get;set;}
    }
    

    inject those dependencies at runtime

    public class SomeClassFactory
    {
      public SomeClass Create()
      {
        var result = new SomeClass();
        DependencyInjector.Inject(result);
        return result;
      }
    }
    

    and the instance is configured in app.config:

    
    
      
        

    Now if you want to change the type of logger, you just go into the configuration and specify another type.

提交回复
热议问题