7

mvc.net と StructureMap を使用して、すべてのリポジトリとサービスをスキャンして登録しています。次に、Singleton で登録してキャッシュしたいと思います。どのようにできるのか?

 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", ""));
            });
        });
4

3 に答える 3

19

2.6 の新しい API を使用すると、ITypeScanner は非推奨になります。代わりに、これを規約として実装する必要があります。簡単な例は、特定のインターフェイスのすべてのタイプがシングルトンであるという規則を登録する場合です。

    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);
        }
    }
于 2010-02-05T18:02:36.727 に答える
2

Jeremy Miller がhttp://codebetter.com/blogs/jeremy.miller/archive/2009/01/20/create-your-own-auto-registration-convention-withで概説しているものと同様の ITypeScanner を実装する必要があります。-structuremap.aspx

たとえば、コントローラーの場合、その Scan 呼び出しを次のように変更します。

x.Scan(y => {
    y.TheCallingAssembly();
    y.With<MyNewTypeScanner>();
});

次に、次のようなクラスを別の場所で定義します。

public class MyNewTypeScanner: ITypeScanner
{
    //This method is responsible for determining if a type should be registered
    // and then passing it to RegisterType() if so
    public void Process(Type type, PluginGraph graph)
    {
        //At this point you would probably just test to see if type is IController
        //but you can get more sophisticated without too much headache.

        this.RegisterType(graph, type);
    }


    private void RegisterType(PluginGraph graph, Type implementingType)
    {
        //The argument passed to FindFamily must be the type/class that will be requested out of SM
        var family = graph.FindFamily(implementingType);

        family.AddType(implementingType);
        family.SetScopeTo(InstanceScope.Singleton);
    }
}

これでうまくいくはずです。

于 2009-06-30T15:10:17.197 に答える