简体   繁体   中英

Inversion of Control / Dependency Injection with good explanation and examples in .net?

Hi

I don't have much knowledge on IoC/DI frameworks in .net framework. Can anyone give me links that explans IoC/DI in detail with few example in C#? I want go through it and get more idea about these frameworks.

So that I can get the knowledge, where and How can I use these frameworks are useful in implementing the project.



nrk

有关DI概念的一般性介绍,包括C#中的综合示例,您可能需要阅读我的书籍.NET中的依赖注入

Your best bet is too look at one of the IOC/DI website

Spring.net http://www.springframework.net/

Castle Windsor http://www.castleproject.org/container/index.html

Structure Map http://structuremap.sourceforge.net/Default.htm

Good articles on comparison of IOC

http://blog.ashmind.com/index.php/2008/08/19/comparing-net-di-ioc-frameworks-part-1/

http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx

I hope that helps. I personally have used Spring.Net and Castle Windsor - the latter probably easier to understand and use.

Have a look at this question as well. Examples of IoC Containers

Aim Kai has mentioned some very good resources on concrete IOC Container implementations and corresponding tutorials, however they are narrowly focused on the IOC Container beeing discussed and less of a general introduction/tutorial.

Personally, I like the introduction Rob Connery wrote best.

It's all about loose coupling.

Imagine you have a class foo that is dependant on class bar

public class Foo
{
      public Foo(Bar bar)
      {
      }
}

Here we have to pass an instance of bar into the class to instantiate it. What happens if we want to have two differant implementations of Bar, one for interacting with a DB and one for testing?

Well we would create and interface IBar and use that instead, then we can use two concrete implementations.

Now consider that we have lots of complex dependencies in lots of classes which are being called in lots of places, if we wanted to change the implementation we would have to change the code in every place a an object implementing IBar is created, that could be a lot of work.

Instead we can use dependancy injection like this.

IUnityContainer myContainer = new UnityContainer();
myContainer.RegisterType<IBar, Bar>();
Foo foo = myContainer.Resolve<Foo>();

Here the unity framework has inserted a Bar object into the Foo's constructor, if you changed the type registration in one place, you change how Foo objects will get resolved all over the place.

When you have complex dependencies that may change, DI is essential!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM