寻找各种实现方式统一使用依赖注入 [英] looking for various way of implemention Dependency injection using unity

查看:52
本文介绍了寻找各种实现方式统一使用依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是依赖注入的新手。我只是很熟悉如何通过接口注入实现依赖注入,但是我们知道依赖注入可以通过三种方式实现,或者可能更多,它们是:-

i am new in Dependency injection. i just got familiar how to implement dependency injection with Interface injection but we know that Dependency injection can be implemented with three way or may be more and those are :-


  1. 接口注入:该服务提供了消费者必须实现的接口。该界面在运行时公开特定的行为。

  2. Setter注入:依赖对象公开了一种 setter方法来注入依赖项。

  3. 构造函数注入:通过类构造函数注入依赖项

  1. Interface injection: The service provides an interface which consumers must implement. The interface exposes specific behaviors at run time.
  2. Setter injection: The dependent object exposes a "setter" method to inject the dependency.
  3. Constructor injection: Dependencies are injected through the class constructor

所以我正在寻找少量示例代码可以帮助我理解如何使用Setter注入或使用unity的Constructor注入实现依赖注入。对于使用小代码实现不同方式实现依赖项注入的任何帮助,将不胜感激。

so i am looking for few sample code which can help me to understand how to implement Dependency injection using either Setter injection or Constructor injection using unity. any help with small small code for different way of implementing dependency injection will be appreciated.

我只知道使用unity进行接口注入。

i know only Interface injection using unity. here is my code which works fine using Interface injection with unity.

public interface ILogger
{
     void Write(string message);
}

We have define three classes as follows.

public class FileLogger : ILogger
{
     public void Write(string message)
     {
          //Do somthing
     }
}

public class SQLLogger : ILogger
{
     public void Write(string message)
     {
          //Do somthing
     }
}

public class WindowsEventLogger : ILogger
{
     public void Write(string message)
     {
          //Do somthing
     }
}

需要在配置文件(即应用程序)中使用接口注册和映射这些类.config)。

Need to register and map these classes with interface in configuration file (i.e. app.config).

<configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>

  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <alias type="UnityTest.ILogger, UnityTest" alias="ILogger" />
    <namespace name="UnityTest"/>

    <container>
      <register mapTo="UnityTest.FileLogger, UnityTest" name="MyFileLogger" type="ILogger"/>
      <register mapTo="UnityTest.SQLLogger, UnityTest" name="MySQLLogger" type="ILogger"/>
      <register mapTo="UnityTest.WindowsEventLogger, UnityTest" name="MyWindowsEventLogger" type="ILogger"/>
    </container>
</unity>

注意:名称属性在寄存器标记中很重要。

Note: name attribute is important in register tag.

最后,我们必须将此映射用于我们的代码中。因此,我们必须知道哪个国家/地区更适合特定国家/地区。

Finally we have to use this map into our code. So, we have to know that for which one is preferable for specific country.

可以使用字典对象来保持此映射,如下所示。

A dictionary object can be use to keep this mapping as follows.

IDictionary<string, string> loggers = new Dictionary<string, string>();
loggers.Add("USA", "MyFileLogger");
loggers.Add("GBR", "MySQLLogger");
loggers.Add("IN", "MyWindowsEventLogger");

您可以从数据库,xml或其他来源填充​​它,现在该调用Write方法了

You can populate it from database, xml or another source, and now it's time to call the Write method.

IUnityContainer container = new UnityContainer();
container.LoadConfiguration();

ILogger logger = container.Resolve<ILogger>(loggers[objUser.countryCode]);
logger.Write("Hello World");



新问题



我找到了一个统一的建筑注入示例代码,但还有一件事尚不清楚。这是代码。

New question

I found a sample code for construction injection with unity but still one thing is not clear. Here is the code.

public class CustomerService
{
  public CustomerService(LoggingService myServiceInstance)
  { 
    // work with the dependent instance
    myServiceInstance.WriteToLog("SomeValue");
  }
} 

IUnityContainer uContainer = new UnityContainer();
CustomerService myInstance = uContainer.Resolve<CustomerService>();

当我们写 uContainer.Resolve< CustomerService>(); ,那么我们将不发送LoggingService类的任何实例,然后再发送 CustomerService 类的实例,因为它的构造函数需要 LoggingService

When we write uContainer.Resolve<CustomerService>(); then we are not sending any instance of LoggingService class then how we can create instance of CustomerService class because it's constructor require instance of LoggingService.

该区域不清楚。请向我解释它的工作原理。

This area is not clear. Please explain to me how it works.

另一个问题是 [Dependency] 属性:它的作用以及作用时间方法需要用 [Dependency] 属性修饰。

Another question is [Dependency] attribute: what it does, and when a method needs to be decorated with the [Dependency] attribute.

推荐答案

以您的代码为基础。

如果您有一些依赖于ILogger的类,并且您具有ILogger的默认注册(没有名称的注册)

if you have some class that depends on ILogger, and you have a default registration for ILogger (a registration without name)

IUnityContainer container = new UnityContainer();

//fixed
//by default RegisterType will create new instance of the type every time 
//the container resolves the dependancy 
container.RegisterType<ILogger,SomeLoggerImplementation>();
container.RegisterType<Foo>();
container.RegisterType<Bar>();

//will create a new instance of SomeLoggerImplementation using a default ctor, pass it to the constructor of Foo and return the instance of Foo
//if SomeLoggerImplementation has some other dependancies they can be registered in the container too! 
var foo = container.Resolve<Foo>();

//will create a new instance of SomeLoggerImplementation using a default ctor, create a new instance of Bar, 
//Set the value of the Property Logger (but not the Logger2), and return the instance of Bar
var bar = container.Resolve<Bar>();

//Constructor injection
public class Foo
{
    private ILogger _logger;
    public Foo(ILogger logger)
    {
        //if Foo is resolved from the container , the value for the logger parameter will be provided from the container
        _logger = logger;
    }
}


//property injection
public class Bar
{
    //If Bar is resolvced from the container the value for the Logger property will also  be provided from the container
    [Dependency]
    public ILogger Logger { get; set; }

    //this will not be injected
    public ILogger Logger2 { get; set; }

    public Bar()
    {
    }
}

这篇关于寻找各种实现方式统一使用依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆