views:

119

answers:

2

Consider the following class

public class SchemaExecutor: ISchemaExecutor
{
    public SchemaExecutor(SqlPlusSettings sqlPlusSettings)
    {
        _sqlPlusSettings = sqlPlusSettings;
    }
...

And container configuration

ObjectFactory.Initialize( x =>
{
    SqlPlusSettings sqlPlusSettings = GetSqlPlusSettings();
    x.ForRequestedType<ISchemaExecutor>().TheDefaultIsConcreteType<SchemaExecutor>()
        .WithCtorArg("sqlPlusSettings").EqualT(sqlPlusSettings);                       
 });

But .WithCtorArg works only for primitives and so the initialization above doesn't work.

Is there any way to configure constructor with non primitive parameter?

+2  A: 

You need to just let the IoC do what it does and inject your dependencies for you...

ObjectFactory.Initialize( x =>
 {
      x.ForRequestedType<SqlPlusSettings>().TheDefaultIsConcreteType<SqlPlusSettings>().AsSingletons;
      x.ForRequestedType<ISchemaExecutor>().TheDefaultIsConcreteType<SchemaExecutor>();
 });

SqlPlusSettings sqlPlusSettings = GetSqlPlusSettings();
ObjectFactory.Inject<SqlPlusSettings>(sqlPlusSettings);

The way you have it here with none of the AutoWiring, I think the redundant line for SqlPlusSettings is needed to let StructureMap know about it. But essentially SM knows about both the SchemaExecutor and the SqlPlusSettings and when instantiating the SchemaExecutor it looks for the parameters, see's that the SqlPlusSettings is a singleton and it already has one and passes it to instantiate the SchemaExecutor.

Mark G
A: 

If you wish to control exactly what instance of the settings object your class will receive you can accomplish this by either configuring the concrete class or per plugin by configuring its dependency.

Note: I am using the trunk but I believe that everything here is available in 2.5.3.

public class MySettings
{

}

public interface IMyClass
{
 MySettings Settings { get; }
}

public class MyClass : IMyClass
{
 public MySettings Settings { get; private set; }

 public MyClass(MySettings settings)
 {
  Settings = settings;
 }
}

[TestFixture]
public class registry_test
{
 [Test]
 public void configure_concrete_class()
 {
  var mySettings = new MySettings();

  var container = new Container(config =>
  {
   config.For<MySettings>().Use(mySettings);
   config.For<IMyClass>().TheDefaultIsConcreteType<MyClass>();
  });

  container.GetInstance<IMyClass>().Settings.ShouldBeTheSameAs(mySettings);
 }

 [Test]
 public void configure_concrete_ctor_dependency()
 {
  var mySettings = new MySettings();

  var container = new Container(config =>
  {
   config.For<IMyClass>().TheDefault.Is.OfConcreteType<MyClass>()
    .CtorDependency<MySettings>().Is(mySettings);
  });

  container.GetInstance<IMyClass>().Settings.ShouldBeTheSameAs(mySettings);
 }
}
KevM