Dependency injection in .NET with examples?

Can someone explain the dependency injection with a basic .NET example and provide some links to .NET resources to extend the theme?

This is not a duplicate. What is dependency injection? because I am asking for specific .NET examples and resources.

+29
dependency-injection
Apr 13 '09 at 13:59
source share
8 answers

Here is a general example. You need to log in to your application. But during development, you are not sure if the client wants to register in the database, files or event log.

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

This is some pseudo code (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;} } 

introduce these 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:

 <?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name ="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/> </configSections> <unity> <typeAliases> <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity" /> </typeAliases> <containers> <container> <types> <type type="MyAssembly.ILog,MyAssembly" mapTo="MyImplementations.SqlLog, MyImplementations"> <lifetime type="singleton"/> </type> </types> </container> </containers> </unity> </configuration> 

Now, if you want to change the registrar type, just go to the configuration and specify a different type.

+32
Apr 13 '09 at 14:19
source share

Ninject should have one of the coolest patterns: (cut from the pattern)

 interface IWeapon { void Hit(string target); } class Sword : IWeapon { public void Hit(string target) { Console.WriteLine("Chopped {0} clean in half", target); } } class Shuriken : IWeapon { public void Hit(string target) { Console.WriteLine("Shuriken tossed on {0}", target); } } class Samurai { private IWeapon _weapon; [Inject] public Samurai(IWeapon weapon) { _weapon = weapon; } public void Attack(string target) { _weapon.Hit(target); } } class WeaponsModule: NinjectModule { private readonly bool _useMeleeWeapons; public WeaponsModule(bool useMeleeWeapons) { _useMeleeWeapons = useMeleeWeapons; } public void Load() { if (useMeleeWeapons) Bind<IWeapon>().To<Sword>(); else Bind<IWeapon>().To<Shuriken>(); } } class Program { public static void Main() { bool useMeleeWeapons = false; IKernel kernel = new StandardKernel(new WeaponsModule(useMeleeWeapons)); Samurai warrior = kernel.Get<Samurai>(); warrior.Attack("the evildoers"); } } 

This, for me, reads very smoothly, before you start your dojo, you can decide how to arm the samurai.

+30
Nov 14 '09 at 9:59
source share

I think it is important that you first learn DI without IoC containers. So I wrote an example that is slowly building up to the IoC container. This is a real example from my work, but still made it basic enough for beginners to grasp the essence of DI. You can find it here: https://dannyvanderkraan.wordpress.com/2015/06/15/real-world-example-of-dependeny-injection/

It is in C # .NET and then uses Unity.

Update after comment:

The corresponding section of the article

"Observe the following changes to the original design:

quick schedule of the situation

We went for the "Injection Designer" template to implement DI, and the refactoring steps:

  • Annotation of the CardPresenceChecker interface by creating the ICardPresenceChecker interface;
  • Indicate that this CardPresenceChecker only works for company X library, changing its name to XCardPresenceChecker;
  • Ask XCardPresenceChecker to implement the ICardPresenceChecker interface;
  • Annotation is that the LogInService property is of type ICardPresenceChecker instead of "knowing exactly which implementation is carried out on board;
  • And last but not least, to require users (other developers) of LogInService to provide any class that at least implements ICardPresenceChecker so that LogInService can perform its task.

The constructor of LogInServices is as follows:

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

So where do you provide LogInService with the implementation of ICardPresenceChecker? Usually you need this โ€œmappingโ€ (in this example, we will map the ICardPresenceChecker to XCardPresenceChecker) in one central place when you run the application, which is conceptually known as โ€œComposition Rootโ€. For a regular console application, which can be void Main in the Program class. Therefore, for this example, this piece of code will be used at the above location:

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

+3
Jun 16 '15 at 12:35
source share

I have an Injection Dependency with a really simple example.

See the class below, you get the whole idea. As you can see, if you do not provide the file, it will use the default settings file, but you can set the settings file, and then the class will use it.

 Public Class ProcessFile Private _SettingsFile As String = "settings.bin" Public Sub New() End Sub Public Sub New(settings As String) _SettingsFile= settings End Sub Public Function ReadFile() As String 'Do stuff based on the settings stored in the _SettingsFile End Function End Class 

Obviously, this is the simplest case. In the real world, you can do the same with class types, for example, you have a database level, and you can switch the base dll database by injecting dependencies, and the code will work with any database as soon as you can provide a valid class (a class that implements the interface you are using).

Once you get the core, you can do it in a larger area and are completely application independent using DI frames such as unity.

+1
Apr 13 '09 at 14:20
source share

You essentially pass all the necessary objects in the constructor. In addition, you can enable them at runtime using an interface recognizer (although this is less typical). You can find great examples on the Ninject website for the first approach, as well as good examples on the Unity website for the second approach. This avoids the need for single player games and makes it easy to reset the replaceable object corresponding to the desired interface.

0
Apr 13 '09 at 14:14
source share

Install the Nuget packages below in the main project of the mvc4 SampleDependency project. Unity.mvc4, unity.webapi and the MicrosoftAsp.Net Web 2.2 web interface.

In a web project

 public static class Bootstrapper { public static IUnityContainer Initialise() { var container = BuildUnityContainer(); DependencyResolver.SetResolver(new UnityDependencyResolver(container)); GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container); return container; } private static IUnityContainer BuildUnityContainer() { var container = new UnityContainer(); // register all your components with the container here // it is NOT necessary to register your controllers // eg container.RegisterType<ITestService, TestService>(); container.RegisterType<IUserDetailLogic, UserDetailLogic>(); container.RegisterType<IUserData, UserData>(); RegisterTypes(container); return container; } public static void RegisterTypes(IUnityContainer container) { } } 
0
Nov 03 '14 at 12:28
source share

Create a database-level project (class library) and add the code below.

 public class UserData : IUserData { public string getUserDetails() { return "Asif"; } } public interface IUserData { string getUserDetails(); } 
0
Nov 04 '14 at
source share

Add a class class library business class logic project and add the code below. Public class UserDetailLogic: IUserDetailLogic {private IUserData _userData = null;

  public UserDetailLogic(IUserData userData) { _userData = userData; } public string getUserDetails() { return _userData.getUserDetails(); } } public interface IUserDetailLogic { string getUserDetails(); } 

In your main project, add the code below to the home controller.

public class HomeController: controller {private readonly IUserDetailLogic _userDetailLogic;

  public HomeController(IUserDetailLogic userDetailLogic) { _userDetailLogic = userDetailLogic; } public ActionResult Index() { ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; string str = _userDetailLogic.getUserDetails(); return View(); } public ActionResult About() { ViewBag.Message = "Your app description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } 
0
Nov 04 '14 at 11:02
source share



All Articles