如何将 Structuremap 配置为通过 Singleton 在 Assembly 和 Cache 中自动扫描类型? [英] How can I configure Structuremap to auto scan type in Assembly and Cache by Singleton?

查看:24
本文介绍了如何将 Structuremap 配置为通过 Singleton 在 Assembly 和 Cache 中自动扫描类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 mvc.net 和 StructureMap 为我扫描和注册所有存储库和服务.现在我想通过单例注册和缓存.我该怎么办?

I am using mvc.net with StructureMap to scan and register all repositories and services for me. Now I want to register and cache by Singleton. How can I do?

 IContainer container = new Container(x => {
            // Register Repositories and Services
            x.Scan(y => {
                y.AssemblyContainingType<SomeRepository>();
                y.AssemblyContainingType<SomeService>();

                y.IncludeNamespaceContainingType<SomeRepository>();
                y.IncludeNamespaceContainingType<SomeService>();
            });   

            // Register Controllers
            x.Scan(y => {
                y.TheCallingAssembly();
                y.AddAllTypesOf<IController>().NameBy(type => type.Name.Replace("Controller", ""));
            });
        });

推荐答案

使用 2.6 中的新 API,不推荐使用 ITypeScanner.这应该作为约定来实现.一个简单的例子是你想注册一个约定,即特定接口的所有类型都是单例:

Using the new API in 2.6, ITypeScanner is deprecated. This should be implemented as a convention instead. A simple example is you want to register a convention that all types of a particular interface are a singleton:

    Scan(a =>
    {
        a.AssemblyContainingType<IMyPluginType>();
        a.With(new SingletonConvention<IMyPluginType>());
        a.AddAllTypesOf<IMyPluginType>();
    });

那么:

    internal class SingletonConvention<TPluginFamily> : IRegistrationConvention
    {
        public void Process(Type type, Registry registry)
        {
            if (!type.IsConcrete() || !type.CanBeCreated() || !type.AllInterfaces().Contains(typeof(TPluginFamily))) return;

            registry.For(typeof(TPluginFamily)).Singleton().Use(type);
        }
    }

这篇关于如何将 Structuremap 配置为通过 Singleton 在 Assembly 和 Cache 中自动扫描类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆