Mugen Injection [ Getting started]
To start working with Mugen Injection you should:
- Download latest version of Mugen Injection from site or NuGet.
- Add the reference to MugenInjection.Core.dll in your project.
- At application startup...
- Create a MugenInjector.
- Register components.
- During application execution...
- Use the MugenInjector to resolve instances of the components.
Add MugenInjection references
The first step is to add MugenInjection references to your project. For this example, we're only using MugenInjection.Core.dll. Other application types may use additional MugenInjection integration libraries.The easiest way to do this is through NuGet. The "MugenInjection" package has all the core functionality you'll need.
Application Startup
For example, we have code like this:public interface IWriter { void Write(string content); } public interface IService { void Process(); } public class ConsoleWriter : IWriter { #region Implementation of IWriter public void Write(string content) { Console.WriteLine(content); } #endregion } public class WriteSomethingService : IService { private readonly IWriter _writer; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="WriteSomethingService"/> class. /// </summary> public WriteSomethingService(IWriter writer) { _writer = writer; } #endregion #region Implementation of IService public void Process() { _writer.Write("Hello MugenInjection."); } #endregion }
// Create your MugenInjector. var injector = new MugenInjector(); //Registering dependency injector.Bind<IWriter>().To<ConsoleWriter>(); injector.Bind<IService>().To<WriteSomethingService>();
Application Execution
During application execution, you'll need to make use of the components you registered. You do this by resolving them from a IInjector.For our sample app, we'll implement the "Process" method to get an instance of IService to call method "Process":
class Program { private static IInjector _injector; static void Main(string[] args) { // Create your MugenInjector. _injector = new MugenInjector(); //Registering dependency _injector.Bind<IWriter>().To<ConsoleWriter>(); _injector.Bind<IService>().To<WriteSomethingService>(); Process(); } private static void Process() { var service = _injector.Get<IService>(); service.Process(); } }
- The "Process" method asks IInjector for an IService.
- IInjector sees that IService maps to WriteSomethingService so starts creating a WriteSomethingService.
- IInjector sees that the WriteSomethingService needs an IWriter in its constructor.
- IInjector sees that IWriter maps to ConsoleWriter so creates a new ConsoleWriter instance.
- IInjector uses the new ConsoleWriter instance to finish constructing the WriteSomethingService.
- IInjector returns the fully-constructed WriteSomethingService for "Process" method to consume.