kmacdonald kmacdonald - 1 month ago 5
C# Question

How to setup a override registration in Structuremap 4.4

So I have container in which i add a registry that defines a default type for a class.

TestRegistry : Registry{
For<Foo>.Use<Foo>();
}


this registry is added at the start of a web service during initialization of the application. directly after adding my all my registries used for the application I need to override the registration of the
Foo
class. So:

Container.Instance.Configure(x =>
{
x.AddRegistry<TestRegistry>();
var fooInstance = new Foo();
x.For<Foo>.Use(fooInstance);
}


When i go to retrieve this instance from my container

var fromContainer = Container.Instance.GetInstance<Foo>();


i am now getting back
null
. if I use get all instances:

var fromContainer = Container.Instance.GetAllInstances<Foo>();


I get back two results. One for each registration. This makes sense.

However, if i try to clear the registration during the second registration:

Container.Instance.Configure(x =>
{
x.AddRegistry<TestRegistry>();
var fooInstance = new Foo();
x.For<Foo>.ClearAll().Use(fooInstance);
}
var fromContainer = Container.Instance.GetInstance<Foo>();


This still returns
null
. I seem to be missing something here. I would expect this to clear out all registrations of
Foo
and use the instance that i registered last.

Any help would be appreciated. Thanks in advance!

Answer

Well I found my answer. It looks like only the Container.Instance does not actually contain the definition until the configuration method is complete. This means that in order to override the implementation you will need to call Container.Instance.Configure() a second time with the override. Once i did this it started to work as expected.