Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection from Multiple Assemblies using Structuremap

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.

like image 993
Afraz Ali Avatar asked Nov 12 '22 14:11

Afraz Ali


1 Answers

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.

like image 130
Afraz Ali Avatar answered Jan 04 '23 01:01

Afraz Ali