开发者

Castle: using an existing (not single) instance for a lower-level dependency

I have a model roughly like this:

public interface IUnitOfWork { }

public class UnitOfWork : IUnitOfWork { }

public interface IService { }

public class Service : IService
{
    public IUnitOfWork UnitOfWork { get; set; }
}

public class ViewModel
{
    public IService Service { get; set; }
}

And a configuration that could be like this:

container.Register(Component.For<IService>().ImplementedBy<Service>()
                            .LifeStyle.Transient
                   Component.For<IUnitOfWork>().ImplementedBy<UnitOfWork>()
                            .LifeStyle.Transient,
                   Component.For<ViewModel>().LifeStyle.Transient);

I need to resolve, at different points, two instances of ViewModel (I'm using a typed factory for this, but let's leave that aside for simplicity and assume I'm using the raw container)

The catch is that I need to resolve two instances of ViewModel at different points (from another ViewModel that knows about both), and they need to share the same IUnitOfWork.

So, something like this:

var vm1 = container.Resolve<ViewModel>();
//...later
var vm2 = container.Resolve<ViewModel>();

Now, it's very easy to share the Service. I'd just have to do something like:

var vm2 = container.Resolve<ViewModel>(new { vm1.Service });

But of cours开发者_如何转开发e the actual model is more complicated (different ViewModels, with more Services each), so that's not an option.

I can pass the UnitOfWork to Resolve, but it doesn't get used by default (which makes sense). Is there any way to use that parameter (probably by registering a delegate somewhere) when resolving the second ViewModel?

I'd like to be able to do the following:

var vm2 = container.Resolve<ViewModel>(new { UnitOfWork });

And get a ViewModel whose Service has that specific UnitOfWork.


If you need to share a component and you cannot set as singleton(rich client) or perwebrequest, you need to use Contextual lifestyle. check this thread see my last comment to downoload contrib w/ Contextual Lifestyle

For you case I assume those 2 ViewModel will be used by 1 View... so View + UoW require Contextual Lifestyle

check also this one too see comments at the end


The solution was to use ContextualLifestyle coupled with a custom factory that kept a reference to the ContainerContext, in order to use the same one when resolving another ViewModel.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜