开发者

StructureMap: how to correctly set up default dependencies

An approach we've taken recently is to include a StructureMap registry in each of our assemblies that set's up the default dependencies.

We use a scanner to do this:

        cfg.Scan(scanner =>
        {
            scanner.TheCallingAssembly();
            scanner.Assembly("Assembly1");
            scanner.Assembly("Assembly2");
            scanner.Assembly("Assembly3");

            scanner.LookForRegistries();
        });

The idea is that we can then override the default dependencies from the main application.

The question is, where should we register these overrides? i.e. before we scan?, after we scan?

Furthermore, does the order of the assemblies specified in the scan expression, effect the order in which the dependencies are registered. So in the example above, would registries contained in the main application (TheCallingAssembly) get overrided by th开发者_运维百科ose in "Assembly3"?

Many thanks

Ben


Registries in TheCallingAssembly will be overridden by those you register in Assembly1, 2 etc.

So if you register ISomeInterface in everyone of those assemblies, the one in Assembly3 will be the default. The ones registered in the others assemblies you can get from structuremap by calling

container.GetAllInstances<ISomeInterface>();

This will return a IList of all the registered ISomeInterface in structuremap.

If you want to override the ones you get by scanning you have to configure the container again for some reason. If you don't do that, the last scanned type is the default.

In this example the ISomeInterface registered in Assembly1 is the default. When you look at the code, one would belive that SomeOtherClass is the default. But it is actually the one registered in Assembly1 that is the default.

var container = new Container(x => {
            x.Scan(scanner =>
            {
                scanner.TheCallingAssembly();
                scanner.Assembly("Assembly1");

                scanner.LookForRegistries();
            });

            x.For<ISomeInterface>().Use<SomeOtherClass>();
        });

So to override the mappings from the scanned assemblies. You have to configure the container again like this example. Here SomeOtherClass is the default for ISomeInterface.

var container = new Container(x => {
            x.Scan(scanner =>
            {
                scanner.TheCallingAssembly();
                scanner.Assembly("Assembly1");

                scanner.LookForRegistries();
            });
        });

container.Configure(x => x.For<ISomeInterface>().Use<SomeOtherClass>());
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜