views:

260

answers:

2

I am new to the structure map but i want to use it in my asp.net site for dependency injection can any one suggest me simple example to use structure map for the dependency injection

+2  A: 

you will need to do something like this:-

StructureMapConfiguration
    .ForRequestedType<IResourceA>()
    .TheDefaultIsConcreteType<ResourceB>()
    .CacheBy(InstanceScope.Singleton);

This tells StructureMap to inject ResourceB when there is a request for ResourceA.

cw22
+1  A: 

Structure Map

You can configure programatically or via configuration file.

Programatical example (there are other ways):

StructureMap.StructureMapConfiguration.ForRequestedType<ISomething>().TheDefaultIsConcreteType<ConcreteSomething>();

then you can get an instance of the configured type using this sort of code:

//The concrete type will be ConcreteSomething

ISomething instance = ObjectFactory.GetInstance<ISomething>();

You can do it in a config file:

<StructureMap MementoStyle="Attribute">
     <DefaultInstance PluginType="Blah.ISomething, Blah.SomethingDLL" PluggedType="Blah.Concrete.ConcreteSomething,Blah.ConcreteDLL"/>
</StructureMap>

and in the main method or Global.asax you can set this config by saying:

 StructureMap.ObjectFactory.Initialize(x => { x.PullConfigurationFromAppConfig = true; });

and use it the same way as above:

ISomething instance = ObjectFactory.GetInstance<ISomething>();

If the concrete class has a constructor that needs instances injected in it, and you have those configured, the concrete types will get injected by the framework.

There are ways of passing parameters to constructors, dealing with Gereric types, creating named instances that are configured with specific constructor/property values. I use this framework and like it very much.

CSharpAtl