1

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

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

谢谢

4

1 回答 1

3

除非有非常充分的理由,否则您应该尽可能多地在代码中注册。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 查询有很多细微的缺陷(例如,它缺少对泛型类型约束的检查),但它适用于常见场景。如果您使用泛型类型约束,则绝对应该切换到支持此功能的框架,因为这确实很难正确处理。

于 2012-09-25T15:14:59.430 回答