I’m trying to put together some code to show this better, but in the meantime, hopefully I can explain my issue in bits.
I use an DataRepository around ORMLite that is per-request so it can easily commit/rollback a transaction if the request throws an error.
container.RegisterAutoWiredAs<DataRepository, IDataRepository>().ReusedWithin(Funq.ReuseScope.Request);
container.Register<IDataRepositoryCache>(new DataRepositoryCacheClientCache());
The DataRepository has an DI reference to the database (obviously) and the cache (a wrapper around ICacheClient)
public DataRepository(IDbConnectionFactory dbFactory, IDataRepositoryCache cache)
{
DbFactory = dbFactory;
Cache = cache;
}
I use the MessageService, which on my development machine just processes messages using InMemoryTransientMessageService.
IMessageService mq = new InMemoryTransientMessageService();
container.Register<IMessageService>(mq);
container.Register(mq.MessageFactory);
mq.RegisterHandler<MyMessage>(m => { return appHost.ServiceController.ExecuteMessage(m); });
Now, the problem occurs inside a normal request, where I call the MessageService.
e.g.
public IDataRepository Data {get; set;}
public object Post(MyRequest request)
{
:
// Data is pointing to the request's DataRepository instance
:
using (var producer = AppHostBase.Instance.TryResolve<IMessageFactory>().CreateMessageProducer())
{
producer.Publish<MyMessage>(new MyMessage {});
}
:
// Data is pointing to same DataRepository instance, but it has been disposed
:
}
When that Publish() returns, the DataRepository in the current request has been disposed. I just assumed that producer.Publisher() would create a new request and therefore its own DataRepository, but that doesn’t seem to be the case - it reuses the existing one. However, it disposes it before returning - which in my case also cleans up resources.
First, is this correct behaviour?
Is there a way around it, or am I doing something fundamentally wrong?
Thanks.