简体   繁体   中英

Castle.Windsor code review

I am using Castle.Windsor in one factory class to create instance of required class. You can find example below.

public class MyFactory : IDisposable
{
    protected readonly IKernel Kernel;

    protected MyFactory(IKernel kernel)
    {
        Contract.Requires<ArgumentNullException>(
            kernel.NotNull(),
            "'kernel' parameter must be initialized.");

        Kernel = kernel;
    }

    public IMyType Create(long param1, long param2)
    {
        return Kernel.Resolve<IMyType>(
            new { numberOfRows, numberOfCells });
    }

    public void Dispose()
    {
        DisposeManagedResources();
    }

    protected virtual void DisposeManagedResources()
    {
        Kernel.Dispose();
    }
}
  1. I am not sure that I need IDisposable here... should I dispose Kernel right after disposing of MyFactory instance?
  2. I am not sure that IKernel (in constructor) is the best way in order to resolve IMyType in Create method. I guess, somebody can suggest a more elegant version :)

Any other ideas?

Thank you advance.

As a general rule, a class should only dispose resources that it owns. Since this resource is supplied from the outside, that class is not responsible for disposing it, unless the ownership for that resource is 'explicitly' passed with it. This explicitness of passing the ownership is usually done through documentation or by using common design patterns. It is quite natural for instance, that a factory method (named CreateXXX ), passes the ownership the caller with the returned instance. DI containers on the other hand contain Get , GetInstance , or Resolve methods, and they don't pass the ownership to the caller.

But besides this, in your case you are dealing with a DI container. A DI container instance should normally live for the total duration of the application. Although containers usually need disposing, calling dispose within this class will clearly be the wrong place to do so. It is not the responsibility of this factory class to do so. Since the container should live for the duration of the application, the correct place to do so is during application teardown. In a ASP.NET application for instance, this will typically be the Application_End event in the global.asax.

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