I am currently using the following code:
public class MyProvider
{
public MyProvider()
{
}
public void Fetch()
{
using (PopClient popClient = new PopClient())
{
....
}
}
}
Because I want to be able to unit test the Fetch method and due to the fact that I can't mock PopClient, I created an interface and a wrapper class that calls into PopClient. My updated code looks like:
public class MyProvider
{
private readonly IPopClient popClient;
public MyProvider(IPopClient popClient)
{
this.popClient = popClient;
}
public void Fetch()
{
using (var pop3 = popClient)
{
....
}
}
}
I am using Ninject for dependency injection and I am not quite sure what kind of effect the using statement will have in the updated code since Ninject already created an instance of PopClient and injected it into the constructor.
Will the using statement dispose of pop3 object and leave the popClient object alone so Ninject can handle it or will the using statement interfere with Ninject?
What is the proper approach in this case? Any insight would be very helpful.
The
pop3
variable will be given the same reference to anIPopClient
object thatpopClient
has, so when theusing
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 perFetch()
call, what you should do is inject a "factory method":Now, when you call
Fetch()
, it will execute the factory method which will return a new reference to anIPopClient
, 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).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.