What happens to using statement when I move to dependency injection

前端 未结 2 1167
自闭症患者
自闭症患者 2021-02-07 00:09

I am currently using the following code:

public class MyProvider
{
    public MyProvider()
    {
    }

    public void Fetch()
    {
        using (PopClient po         


        
相关标签:
2条回答
  • 2021-02-07 00:25

    The pop3 variable will be given the same reference to an IPopClient object that popClient has, so when the using statement is over, the object referred to by both the local and instance variables will be Dispose()d, probably placing it in an inconsistent state for further use.

    If you want to use multiple instances of IPopClient, one per Fetch() call, what you should do is inject a "factory method":

    public class MyProvider
    {
        private readonly Func<IPopClient> createPopClient;
    
        public MyProvider(Func<IPopClient> popClientFactory)
        {
            this.createPopClient = popClientFactory;
        }
    
        public void Fetch()
        {
            using (var pop3 = createPopClient())
            {
                ....
            }
        }
    }
    

    Now, when you call Fetch(), it will execute the factory method which will return a new reference to an IPopClient, which can be used and then disposed of without affecting any other call to that method.

    AutoFac supports injecting factory methods for registered types without any additional setup (hence it's name, I think); I believe when configuring a Ninject container you are required to explicitly register a "getter" as the factory method for a given return type (which can be as simple as a lambda ()=>new PopClient() or it can use a call to the container's resolution method).

    0 讨论(0)
  • 2021-02-07 00:25

    When setting up your bindings, declare the scope:

    https://github.com/ninject/ninject/wiki/Object-Scopes

    Ninject will call dispose on the objects it created for you, so make sure you write up your dispose methods in any objects you give to Ninject to handle.

    0 讨论(0)
提交回复
热议问题