DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • SwiftData Dependency Injection in SwiftUI Application
  • jQuery vs. Angular: Common Differences You Must Know
  • Angular Best Practices For Developing Efficient and Reliable Web Applications
  • Building Web Applications With .NET: Best Practices and Techniques

Trending

  • Chronicle Services: Low Latency Java Microservices Without Pain
  • Log Analysis Using grep
  • Hugging Face Is the New GitHub for LLMs
  • Breaking Down Silos: The Importance of Collaboration in Solution Architecture
  1. DZone
  2. Software Design and Architecture
  3. Security
  4. StructureMap - Don't Scan All Assemblies

StructureMap - Don't Scan All Assemblies

Mihai Huluta user avatar by
Mihai Huluta
·
Sep. 14, 13 · Interview
Like (0)
Save
Tweet
Share
20.14K Views

Join the DZone community and get the full member experience.

Join For 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.



Assembly (CLI) Dependency injection

Opinions expressed by DZone contributors are their own.

Related

  • SwiftData Dependency Injection in SwiftUI Application
  • jQuery vs. Angular: Common Differences You Must Know
  • Angular Best Practices For Developing Efficient and Reliable Web Applications
  • Building Web Applications With .NET: Best Practices and Techniques

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: