开发者

using UnityConfiguration

开发者 https://www.devze.com 2023-04-04 17:56 出处:网络
I\'m using UnityConfiguration with an MVC application and I\'m trying to register some t开发者_如何学Cypes using the code

I'm using UnityConfiguration with an MVC application and I'm trying to register some t开发者_如何学Cypes 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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号