S. Peter S. Peter - 1 month ago 9
C# Question

Autofac Owned<>

I don't quite understand the difference between Autofac Owned and not Owned disposable components.

interface IMessageHandler
{
void Handle(Message message);
}

class MessagePump
{
Func<Owned<IMessageHandler>> _handlerFactory;

public MessagePump(Func<Owned<IMessageHandler>> handlerFactory)
{
_handlerFactory = handlerFactory;
}

public void Go()
{
while(true)
{
var message = NextMessage();

using (var handler = _handlerFactory())
{
handler.Value.Handle(message);
}
}
}
}


What would be difference between the above code to the following:

interface IMessageHandler
{
void Handle(Message message);
}

class MessagePump
{
Func<Owned<IMessageHandler>> _handlerFactory;

public MessagePump(Func<IMessageHandler> handlerFactory)
{
_handlerFactory = handlerFactory;
}

public void Go()
{
while(true)
{
var message = NextMessage();

using (var handler = _handlerFactory())
{
handler.Handle(message);
}
}
}
}


They are both disposed manually when I choose, what is the difference than?

Answer

Your second code sample would not compile, as handlerFactory constructor parameter and _handlerFactory field are of different type.

Using Owned<T> informs Autofac you do not want Autofac to dispose your dependency, beacuse you are going to do it by yourself. Then - you can/should use using statement or call Dispose() directly in your code to dispose the dependency, Dispose() would not be called automatically.

When you are not going to use Owned<T> dependency, you do not dispose your dependencies by yourself - Autofac would do it for you, when necessary. You do not have to use using statement, you do not have to remember whether the dependency is disposable or not.