Dependency Injection in .NET with examples?

前端 未结 8 1499
别跟我提以往
别跟我提以往 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:06

    I think it is important that you first learn DI without IoC Containers. So therefor I've written an example that slowly builts up to an IoC Container. It's a real example from my work, but still made basic enough for novices to grab the essence of DI. You can find it here: https://dannyvanderkraan.wordpress.com/2015/06/15/real-world-example-of-dependeny-injection/

    It's in C#.NET and later on it uses Unity.

    Update after comment:

    Relevant section of article

    "Observe the following changes to the original design:

    We went for the “Constructor Injection” pattern to implement DI and the refactoring steps were:

    1. Abstract the interface of CardPresenceChecker by creating Interface ICardPresenceChecker;
    2. Make explicit that this CardPresenceChecker only works for the library of Company X, by changing its name to XCardPresenceChecker ;
    3. Have XCardPresenceChecker implement Interface ICardPresenceChecker ;
    4. Abstract the property of LogInService to be of type ICardPresenceChecker instead of ‘knowing’ exactly which implementation is held aboard;
    5. And last but not least, demand from users (other developers) of LogInService that they provide any class that at least implements ICardPresenceChecker so that LogInService can do its thing.

    LogInService’s constructor looks like:

    this.myCardPresenceChecker = cardPresenceChecker;
    this.myCardPresenceChecker.CardIn += MyCardPresenceChecker_CardIn;
    this.myCardPresenceChecker.CardOut += MyCardPresenceChecker_CardOut;
    this.myCardPresenceChecker.Init();
    

    So where do you provide LogInService with an implementation of ICardPresenceChecker? You usually want this ‘mapping’ (in this example we would ‘map’ ICardPresenceChecker to XCardPresenceChecker) at one central place at the startup of an application, known conceptually as the “Composition Root”. For an ol’ regular Console Application that could be the void Main in the Program class. So for this example, this piece of code would be used at the aformentioned place:

    LogInService logInService = new LogInService(new XCardPresenceChecker());"

提交回复
热议问题