How to define a default constructor by code using StructureMap?
Asked Answered
L

3

16

I can't figure out how to define the default constructor (when it exists overloads) for a type in StructureMap (version 2.5) by code.

I want to get an instance of a service and the container has to inject a Linq2Sql data context instance into it.

I wrote this in my 'bootstrapper' method :

ForRequestedType<MyDataContext>().TheDefault.Is.OfConcreteType<MyDataContext>();

When I run my app, I got this error :

StructureMap Exception Code: 202
No Default Instance defined for PluginFamily MyNamespace.Data.SqlRepository.MyDataContext, MyNamespace.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

If I comment out all Linq2Sql generated contructors that I don't need, it works fine.

Update : Oh, and I forgot to say that I would not use the [StructureMap.DefaultConstructor] attribute.

Lontson answered 14/11, 2008 at 8:34 Comment(0)
T
31

You can specify a constructor with the ConstructedBy(). Please try this:

ForRequestedType<MyDataContext>().TheDefault.
Is.ConstructedBy(() => new MyDataContext());

This worked for me.

Trooper answered 18/11, 2008 at 10:35 Comment(3)
Updated SM 2.6 Syntax: For<MyDataContext>().Use(() => new MyDataContext());Mammalogy
It appears in SM 2.6.2 that the Use does not have any constructor arguments.Closing
Tested in SM 2.6.4.1: For<IFoo>().Use(() => new Foo());Fructificative
Y
5

I'm assuming you'd also need to set the object lifetime (InstanceScope) if you are using Linq2Sql. I'd suggest using this code because it give you a little more flexibility.

ForRequestedType< MyDataContext >()
            .CacheBy( InstanceScope.PerRequest )
            .TheDefault.Is.OfConcreteType< MyDataContext >()

SelectConstructor< MyDataContext >( () => new MyDataContext());

With this code you can also further inject interfaces definitions into the MyDataContext constructor like this

SelectConstructor< MyDataContext >( () => new MyDataContext((IDatabaseFactory)null ));

Just remember to define the concrete type with StructureMap for your IDatabaseFactory instance.

Year answered 13/3, 2010 at 4:11 Comment(0)
M
0

I'm not sure how / if it can be done with the fluent interface / internal DSL. You can however use an attribute, if you're not fussed about polluting your domain?

Tag your preferred constructor with [DefaultConstructor] StructureMap defaults to the greediest constructor by convention (constructor with the most parameters).

Madancy answered 14/11, 2008 at 9:14 Comment(2)
Sorry Cik, I'd already typed (but not submitted) my response during your update.Madancy
No problem, my fault ;-) Thanks for your reply anyway ! The approach of annotating my DataContext (in creating a partial class) would be possible but I think that it looses from the benefit of using an IoC ...Lontson

© 2022 - 2024 — McMap. All rights reserved.