0

Here is the sequence in which objects need to be created. I'd like to initialize the whole thing in SM and only use the last one as target:

var firstObject = new FirstClass("First", "Last");
var servers = new List<FirstClass> { firstObject };
var secondObject = new SecondClass();
secondObject.Servers = servers;
var thirdObject = new ThirdClass(secondObject);
var fourthObject = thirdObject.SomeGetFunction(thirdObject);

After all this is configured in SM, I'd like to basically only use

var objectToUse = ObjectFactory.GetInstance<fourthObject>();

So far I'm only able to get half way there, but can not figure out how complete this whole configuration. First three objects are singletons, they are only needed to properly instantiate and configure the fourth one.

4

1 回答 1

0

Here is how this can be accomplished. I'm not sure if this follows the best practices but gets the job done.

The first object to be created needs some settings from the config file; this was easy.

For<FirstClass>()
     .Singleton()
     .Use<FirstClass>()
     .Ctor<string>("First").EqualToAppSetting("FirstKey")
     .Ctor<string>("Last").EqualToAppSetting("LastKey");

The second one was more problematic because after creation two properties needed to be set and one of them was of type IEnumerable<FirstClass>, which I couldn't figure out how set up. As it turns out SM's 'context' object and interception was the answer.

For<SecondClass>()
     .Singleton()
     .Use<SecondClass>()
     .OnCreationForAll((context,x) => 
                           {
                               var server = new FirstClass[1];
                               server[0] = context.GetInstance<FirstClass>();
                               x.Servers = server;
                               x.Connections = 1;
                           });

Third one was again easy, we can let SM figure out dependencies.

For<ThirdClass>().Singleton().Use<ThirdClass>();

And the fourth and final one was tricky again since the object I was after was supposed to be created by a call to the ThirdClass. Again, build in 'context' proved to be useful here.

For<FourthClass>()
      .Singleton()
      .Use(context => context.GetInstance<ThirdClass>().SomeGetFunction("stringParam"));

Now all I have to do is to call ObjectFactory.GetInstance<FourthClass> and do operations from there.

于 2012-07-10T22:58:28.303 回答