Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

StructureMap - Don't Scan All Assemblies

DZone's Guide to

StructureMap - Don't Scan All Assemblies

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

In one of my projects (.NET based - using the Web API), I am using StructureMap as a dependency injection tool. The basic setup I have for it is that for each assembly where dependency injection is required, I have a dependency resolution class which extends the StructureMap Registry class. Here is a simple and clear example:

namespace Security.DependencyResolution
{
    public class SecurityRegistry : Registry
    {
        public SecurityRegistry()
        {
            Scan(config =>
                        {
                            config.WithDefaultConventions();
                            config.AssembliesFromApplicationBaseDirectory();
                            config.IncludeNamespace("Data.Repositories");
                            config.IncludeNamespace("Security");
                        });
                    }

        public static void Initialize(IContainer container)
        {
            container.Configure(ct => ct.Scan(scan =>
                                                {
                                                    scan.LookForRegistries();
                                                    scan.TheCallingAssembly();
                                                }));
        }
    }
}

I want to focus on the AssembliesFromApplicationBaseDirectory method since this is the one that caused me some head pain today. When AssembliesFromApplicationBaseDirectory gets invoked, the base directory of the current application domain is traversed, and any assembly found is added to the scanning operation. Note that I am also using WithDefaultConventions, which informs the scanner that any concrete class named Product, for example, implements an interface named IProduct, and it gets added to PluginTypeIProduct. This will spare you from using explicit declarations of PluginTypes for <IProduct>().Use<Product>().

Because the application has multiple layers, the dependencies are quite intricate.  This is why I thought that if I use AssembliesFromApplicationBaseDirectory in the scanner configuration, it would be a great idea. Well, I was wrong, because I ended up with the following exception, which was thrown every time StructureMap was bootstrapping:

StructureMap configuration failures: Error: 170 Source: Registry: StructureMap.Configuration.DSL.Registry, StructureMap, Version=2.6.4.0, Culture=neutral, PublicKeyToken=e60ad81abae3c223 Unable to find the exported Type's in assembly System.Web.Http, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35. One or more of the assembly's dependencies may be missing. Could not load file or assembly 'System.Net.Http.Formatting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) System.IO.FileLoadException: Could not load file or assembly 'System.Net.Http.Formatting, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. It was obvious that StructureMap was checking "all" assemblies from the base directory of current application domain. That is not what I intended to happen, there are system assemblies which are not needed in the dependency injection. I might say that I was lucky that this exception came to light, because this determined me to add some filtering into the process. If you check StructureMap documentation you will notice that AssembliesFromApplicationBaseDirectory has an overload which accepts a predicate, based on it, it will filter the assemblies which should be added to the scanning operation. So what I did is that I have defined a local array which holds the name of the assemblies which should be added to the scanning operation and used it in the filtering predicate.


It was obvious that StructureMap was checking "all" assemblies from the base directory of the current application domain. That is not what I intended.  There are system assemblies that are not needed in the dependency injection. I might say that I was lucky that this exception came to light, so I decided to add some filtering into the process. If you check StructureMap documentation, you will notice that AssembliesFromApplicationBaseDirectory has an overload that accepts a predicate.  Based on the predicate, it will filter the assemblies that should be added to the scanning operation. So what I did is define a local array that holds the name of the assemblies that should be added to the scanning operation and used it in the filtering predicate.


namespace  Security.DependencyResolution
{
    public class SecurityRegistry : Registry
    {
        public SecurityRegistry()
        {
            var assemblies = new[] { "Data.Repositories", " Security" };
            Scan(config =>
                        {
                            config.AssembliesFromApplicationBaseDirectory(assembly => assemblies.Contains(assembly.FullName));
                            config.IncludeNamespace("Data.Repositories");
                            config.IncludeNamespace("Security");
                        });
                    }

        public static void Initialize(IContainer container)
        {
            container.Configure(ct => ct.Scan(scan =>
                                                {
                                                    scan.LookForRegistries();
                                                    scan.TheCallingAssembly();
                                                }));
        }
    }
}


Besides that, I decided to drop WithDefaultConventions in favor of explicit declaration. At least this will make things more obvious, even though it is more verbose. The conclusion is: Don't take shortcuts, not unless you are 100 percent sure it will work properly under any circumstances.



Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

Topics:
dotnet ,.net & windows ,inverse of control ,structuremap ,dependecy injection

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}