简体   繁体   中英

Can I inject into an ASP.NET MVC controller, some strings (eg. configuration values) using StructureMap?

I'm using structureMap as my IoC/DI for an ASP.NET MVC web site. Works great.

Normally, I have my controllers that pass in Interfaces and structureMap + greedy constructors == works great.

eg.

public void FooController : Controller
{
    public FooController(IPewPew pewPew) { .. }
}

etc..

But.. one of my controllers (and only one of em) would like to have two strings to be passed in.

eg..

public void FooController2 : Controller
{
    public FooController2(IPewPew pewPew, string aaa, string bbb) { .. }
}

Is there any ways I can do this with StructureMap? Is there a way to say, when a string "aaa" is listed, then use this value => "hi!";

I didn't really want to put all those strings, into a concrete class with an interface.

It's like I want to say something like.

For<string>().WithName("aaa").Use<string>().WithValue("hi");

Cheers!

This worked for me:

ObjectFactory.Configure( x=>
{
    x.For<FooController2>()
     .Use<FooController2>()
     .Ctor<string>("aaa")
     .Is("hi");
});

You can register a Func<T> delegate, which allows you to have a type safe registration.

container.Configure(r => r.For<FooController2>().Use(() =>
{
    var pewPew = container.GetInstance<IPewPew>();  
    return new FooController2(pewPew, "someValue", "anotherValue");
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM