Dependency Injection Initialization

前端 未结 5 1752
天涯浪人
天涯浪人 2021-02-06 14:47

Please note: I have just started using AutoFac to learn about DI and IoC.

Is dependency injection supposed to be initialized in the controllers constructor?

Ho

5条回答
  •  盖世英雄少女心
    2021-02-06 15:44

    Dependency injection is not trivial - the concept is simple, but understanding it might require some practice and research. Let me give you an example of a place where DI is used, perhaps it will make sense (might not be the best example, sorry I can't think of anything better ATM):

    So say you have the following class:

    public class MyAwesomeClass {
       private readonly IConfig _config;
    
       public MyAwesomeClass(IConfig config) {
          _config = config;
       }
    
       public IEnumerable GetFiltered() {
          IEnumerable results = _config.GetSettings();
    
          // filter my results
          return results.Where(x => x.StartsWith("awesome", StringComparison.OrdinalIgnoreCase));
       }
    }
    

    Now if you're to test GetFiltered you can inject a fake implementation of IConfig and make sure that your filter is working correctly (you isolate your code from depdendencies). You also invert the control by exposing the dependencies and letting the user of your class take care of them, you're pretty much saying - "If you want me to work I need to you to give me an implementation of IConfig, you take care of it."

    Here is how the test might look like

    [Test]
    public void GetsOnlyResultsContainingAwesome() {
       var fakeConfig = new FakeConfig();
       var awesome = new MyAwesomeClass(fakeConfig);
    
       IEnumerable results = awesome.GetFiltered();
    
       Assert.AreEqual(2, results.Count());        
    }
    

    Here is the fake implementation of IConfig

    public class FakeConfig : IConfig {
       public IEnumerable GetSettings() {
          return new List { "test1", "test2", "awesome1", "awesome2" };
       }
    }
    

    I hope this makes sense. Sorry if my example is not good, but I'm just trying to illustrate a point.

提交回复
热议问题