Search code examples
c#structuremapstructuremap3

How to use Auto Registration and Type Scanning in Structuremap


In my solution I have three projects like this. enter image description here

I copy Common.dll and Service.dll in a folder like d:\libs and use the below code with type scan

 ObjectFactory.Initialize(x =>
           {
              x.Scan(xx =>
               {
                   xx.AssembliesFromPath(@"d:\libs");
                   xx.LookForRegistries();
               });
           });
//I have PersonService that implement IPersonService
namespace Common
{
    public interface IPersonService
    {
        string SayHello(string name);
    }
}
namespace Services
{
    public class PersonService : IPersonService
    {
        public string SayHello(string name)
        {
            return string.Format("Hello {0}", name);
        }
    }
}

After Initialize my dependencies when I want get instance from IPerson I get this error

  var personService = ObjectFactory.GetInstance<IPersonService>();

{"No default Instance is registered and cannot be automatically determined for type 'Common.IPersonService'\r\n\r\nThere is no configuration specified for Common.IPersonService\r\n\r\n1.) Container.GetInstance(Common.IPersonService)\r\n"}


Solution

    • Add xx.WithDefaultConventions(); as well.
    • And when you are designing a plugin system by using StructureMap, the host project shouldn't have a reference to any of the plugins. Only the interface/contract plugin should be referenced and this assembly shouldn't be copied to d:\libs folder. In other words, the current application domain shouldn't have 2 instances of any assemblies. So if you want to use IPersonService interface in the host program directly, add a reference to Common.dll and don't copy it to d:\libs folder to avoid duplication. And now the host project shouldn't have a reference to Services.dll too.