使用Unity配置

发布于 2024-12-04 06:02:09 字数 593 浏览 0 评论 0原文

我正在将 UnityConfiguration 与 MVC 应用程序一起使用,并且我尝试使用代码注册某些类型

container.Configure(a => a.Scan(b => b.Include(
              t => t.IsSubclassOf(typeof(ActionFilterAttribute)))));

,但是它似乎没有按类型注册。 确实,我也可以使用

GetType()
     .Assembly
     .GetTypes()
     .Where(t => t.IsSubclassOf(typeof(ActionFilterAttribute)))
     .ToList()
     .ForEach(r => container.RegisterType(r));

,但它不具有相同的可读性。

也许我不明白“配置”(扩展)方法应该做什么。

谢谢, 弗罗林

I'm using UnityConfiguration with an MVC application and I'm trying to register some types using the code

container.Configure(a => a.Scan(b => b.Include(
              t => t.IsSubclassOf(typeof(ActionFilterAttribute)))));

But it does not seem to register by types.
True, I could also use

GetType()
     .Assembly
     .GetTypes()
     .Where(t => t.IsSubclassOf(typeof(ActionFilterAttribute)))
     .ToList()
     .ForEach(r => container.RegisterType(r));

but it does not have the same readability.

Maybe I don't understand what the "configure" (extension) method is supposed to do.

Thanks,
florin

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

╰沐子 2024-12-11 06:02:09

当您想要按照约定自动注册类型而不是为每种类型手动配置容器时,请使用扫描仪。

至少,在使用扫描仪时,您必须指定要扫描的程序集以及要使用的约定:

container.Configure(c => c.Scan(scan =>
{
    scan.AssembliesInBaseDirectory();
    scan.With<FirstInterfaceConvention>();
    scan.Include(t => t.IsSubclassOf(typeof(ActionFilterAttribute)));
}));

有几件事值得一提:

  1. 如果内置约定不适合您,您只需创建一个实现 IAssemblyScannerConvention 接口的类,并将示例中的 FirstInterfaceConvention 替换为您的类型即可自行创建。

  2. 通过使用 scan.Include(...),您隐式地排除了所有其他类型的注册。

  3. 看起来您正在尝试注册一个具体的类(属性)。这在 Unity 中不是必需的,因为它可以解析具体类,而无需先注册它们。

希望这有帮助!

-托马斯

The scanner is used when you want to automatically register types by a convention instead of manually configure the container for every type.

As a minimum, when using the scanner, you have to specify the assemblies you want to scan as well as which convention you want to use:

container.Configure(c => c.Scan(scan =>
{
    scan.AssembliesInBaseDirectory();
    scan.With<FirstInterfaceConvention>();
    scan.Include(t => t.IsSubclassOf(typeof(ActionFilterAttribute)));
}));

A couple of things worth mentioning:

  1. If the built-in conventions doesn't suit you, you can make your own simply by creating a class that implements the IAssemblyScannerConvention interface and replace the FirstInterfaceConvention in the example with your type.

  2. By using scan.Include(...) you implicitly excludes all other types from being registered.

  3. It looks like you are trying to register a concrete class (attribute). This is not necessary in Unity as it can resolve concrete classes without them being registered first.

Hope this helps!

-Thomas

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文