2
\$\begingroup\$

I'm in the process of refactoring one of my open source projects, branch here.

The basic idea of the refactor is to allow for classes and all of its children in the graph to be scoped. I wrote a blog post about it here.

The container is abstracted into an interface:

public interface IScopedContext : IDisposable
{

}



public interface IScopedContext<out TEntryPoint> : IScopedContext where TEntryPoint : class
{
    TEntryPoint EntryPoint { get; }
}

StructureMap implementation:

internal sealed class StructureMapScopedContext<TEntryPoint> : IScopedContext<TEntryPoint> where TEntryPoint : class
{
    private readonly IContainer nested;

    public StructureMapScopedContext(IContainer container)
    {
        nested = container.GetNestedContainer();
        nested.Configure(config => config.For<IScopedContext>().Use(this));
        EntryPoint = nested.GetInstance<TEntryPoint>();
    }

    public TEntryPoint EntryPoint { get; private set; }

    public void Dispose()
    {
        nested.Dispose();
    }
}

Basically after refactoring you can do:

public class Host
{
    private readonly IScopedContext<MyWorker> myWorkerContext;

    public Host(IScopedContext<MyWorker> myWorkerContext)
    {
        myWorkerContext = myWorkerContext;
    }

    public void Start()
    {
        using(myWorkerContext)
        {
            myWorkerContext.EntryPoint.Start();
        }
    }
}

Is it a solid design? Any pitfalls?

\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.