Get a new instance with StructureMap
- by Aligned
It took me too long to figure this out, so hopefully it will help you. StructureMap has way that will create a new instance of the object every time, instead of storing this in the container. I’m going to use this for the DBContext and for WCF Service references. Since the ObjectFactory is a static class, MVC will have these stored in memory without this.
Credit goes to Joshua Flanagan for answering my question.[TestMethod]
public void GetConcreteInstanceOf_ShouldReturn_DifferentInstance()
{
ObjectFactory.Initialize(registry =>
{
// set it up so that it's new every time
// use this for DBContext and service references
registry.For<ISystemDataService>().Use(() => new SystemDataService());
});
ISystemDataService result = Resolver.GetConcreteInstanceOf<ISystemDataService>();
ISystemDataService result2 = Resolver.GetConcreteInstanceOf<ISystemDataService>();
Assert.AreNotSame(result, result2);
}