【问题标题】:How to inject with Spring.NET multiple implementations from common interface?如何从公共接口注入 Spring.NET 多个实现?
【发布时间】:2014-12-03 01:37:51
【问题描述】:

Unity 有一个很棒的特性,它提供了一种从通用接口注入多个实现的方法。

它解析特定实现的方式是按名称。

这是example

我想知道如何用 Spring.NET 做同样的事情。

例如,我有以下对象,其中 A 和 B 解析器使用相同的接口。

遵循弹簧配置:

<?xml version="1.0" encoding="utf-8"?>

<objects xmlns="http://www.springframework.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd http://www.springframework.net/aop http://www.springframework.net/xsd/spring-aop.xsd" xmlns:db="http://www.springframework.net/database" xmlns:aop="http://www.springframework.net/aop" xmlns:tx="http://www.springframework.net/tx">

    <object id="A" type="Program.Mappers.Resolvers.A, Program"></object>

    <object id="B" type="Program.Mappers.Resolvers.B, Program"></object>

</objects>

Spring.NET 不接受这一点,因为两个对象使用相同的接口。

我该如何解决?

【问题讨论】:

  • 我已经添加了完整的XML spring 配置内容。

标签: c# dependency-injection dependencies spring.net


【解决方案1】:

任何 IApplicationContext 都是 IObjectFactory,并且此接口具有执行该操作的方法。

//
// Summary:
//     Return an instance (possibly shared or independent) of the given object name.
//
// Parameters:
//   name:
//     The name of the object to return.
//
// Type parameters:
//   T:
//     The type of the object to return.
//
// Returns:
//     The instance of the object.
//
// Exceptions:
//   Spring.Objects.Factory.NoSuchObjectDefinitionException:
//     If there's no such object definition.
//
//   Spring.Objects.Factory.ObjectNotOfRequiredTypeException:
//     If the object is not of the required type.
//
//   Spring.Objects.ObjectsException:
//     If the object could not be created.
//
// Remarks:
//      This method allows an object factory to be used as a replacement for the
//     Singleton or Prototype design pattern.
//     Note that callers should retain references to returned objects. There is
//     no guarantee that this method will be implemented to be efficient. For example,
//     it may be synchronized, or may need to run an RDBMS query.
//     Will ask the parent factory if the object cannot be found in this factory
//     instance.
T GetObject<T>(string name);

【讨论】:

  • Spring.Net 旨在提高 IoC 和 DI 功能,如果您的生态系统中的许多类都向容器请求依赖项,那么您做错了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 2019-05-27
  • 1970-01-01
  • 2014-11-16
  • 2020-05-22
  • 2018-10-03
  • 2019-04-09
相关资源
最近更新 更多