Dependency Injection from Multiple Assemblies using Structuremap
Asked Answered
I

1

6

I am new to DI concept and new to structuremap. I am trying to full fill a scenario where all my interfaces are in AssemblyA and all my implementations are in AssemblyB. I want to use Structuremap to inject instance of AssemblyB class in constructor which has dependency on interface from AssemblyA

public class Customer(ICustomerService)
{

}

ICustomerService is in AssemblyA and CustomerService class is in assemblyB. I want Structuremap to inject CustomerService instance in this constructor. I am assuming that if the name of class is same as the name of interface prefixed with and I. Structuremap will recognize it automatically.

I have written the following configuration.

 x =>
        {


            x.Scan(scan =>
                {
                    scan.Assembly("AssemblyA");
                    scan.Assembly("AssemblyB");
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
            });

but it gives me error

StructureMap Exception Code:  202
No Default Instance defined for PluginFamily AssemblyA.ICustomerService, AssemblyA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

I want to use the default conventions and avoid registering each interface to a class.

Impracticable answered 3/1, 2013 at 15:9 Comment(0)
I
2

Ok, I got it to work but I am even more confused now.

This code seems to work

IContainer container = new Container(c =>
            {
                c.Scan(x =>
                {
                    x.Assembly("AssemblyA");
                    x.Assembly("AssemblyB");
                    x.IncludeNamespace("AssemblyA");
                    x.TheCallingAssembly();
                    x.WithDefaultConventions();
                });
            });

Here I have simple added x.IncludeNamespace("AssemblyA"); after the AssemblyB scan thinking that it needs this namespace and it has started working.

My problem is solved but I don't know what was wrong or if this is the right way to go. Any help will still be greatly appreciated.

Impracticable answered 4/1, 2013 at 11:44 Comment(1)
Ok, I was able to understand what was happening. I had multiple classes that were implementing the Interface in different assemblies that I was scanning. This produces the original error that I reported in the question. The code that I posted in the question should work correctly if there is only one class that satisfies the Default Convention of SM in all the scanning assemblies. My bad for not getting to it earlier but hope it helps anyone banging his head. As soon as I added the x.IncludeNamespace("AssemblyA"); line basically I filtered the class assembly for SM and it started working :)Impracticable

© 2022 - 2024 — McMap. All rights reserved.