【问题标题】:Configuring Unity container using XML or web.config使用 XML 或 web.config 配置 Unity 容器
【发布时间】:2012-09-25 14:16:20
【问题描述】:

我正在使用 .net 4.5 和 MVC4。 我按照以下帖子中的描述实现了 Unity IoC:http://kennytordeur.blogspot.com/2011/05/aspnet-mvc-3-and-unity-using.html

但我希望能够使用外部 XML 或在 web.config 中“注册”我的存储库类型。这可能吗?样品将不胜感激。

谢谢

【问题讨论】:

标签: c# asp.net .net asp.net-mvc-3 unity-container


【解决方案1】:

除非有非常充分的理由,否则您应该尽可能多地在代码中注册。 XML 配置更容易出错、冗长,并且很快就会成为维护的噩梦。无需在 XML 中注册(所有)您的存储库类型(这可以使用 Unity),只需将包含存储库类型的程序集名称放入配置中并在代码中动态注册它们。这使您不必在每次添加新的存储库实现时都更改配置。

这是一个例子。

在您的配置文件中,使用程序集的名称添加一个新的 appSetting:

<appSettings>
    <add key="RepositoryAssembly" value="AssemblyName" />
</appSettings>

在您的作文根目录中,您可以执行以下操作:

var assembly = Assembly.LoadFrom(
    ConfigurationManager.AppSettings["RepositoryAssembly"]);

// Unity misses a batch-registration feature, so you'll have to
// do this by hand.
var repositoryRegistrations =
    from type in assembly.GetExportedTypes()
    where !type.IsAbstract
    where !type.IsGenericTypeDefinition
    let repositoryInterface = (
        from _interface in type.GetInterfaces()
        where _interface.IsGenericType
        where typeof(IRepository<>).IsAssignable(
            _interface.GetGenericTypeDefinition())
        select _interface)
        .SingleOrDefault()
    where repositoryInterface != null
    select new
    {
        service = repositoryInterface, 
        implemention = type
    };

foreach (var reg in repositoryRegistrations)
{
    container.RegisterType(reg.service, reg.implementation);
}

LINQ 查询有很多细微的缺陷(例如,它缺少对泛型类型约束的检查),但它适用于常见场景。如果您使用泛型类型约束,则绝对应该切换到支持此功能的框架,因为这确实很难做到。

【讨论】:

  • 注意:从 v3 开始,Unit 包含批量注册功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-26
  • 2016-08-14
  • 1970-01-01
  • 2011-07-29
相关资源
最近更新 更多