在StructureMap中注册默认实例 [英] Register a default instance in StructureMap

查看:68
本文介绍了在StructureMap中注册默认实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类(MyService),该类具有静态属性(MyService.Context),该属性表示当前上下文(特定于当前登录的用户,因此会发生变化).

I have a class (MyService) that has a static property (MyService.Context) which represents a current context (which is specific to currently logged in user, so it changes).

我正在努力实现的目标

ObjectFactory.Initialize(x =>
            {
                x.For<IMyService>().Use<MyInstance>(c => c.Use(MyService.Context));
            });

即这样,对于每个ObjectFactory.GetInstance<IMyService>(),我都会获得对MyService.Context

I.e. so that for every ObjectFactory.GetInstance<IMyService>() i get a reference to MyService.Context

那可行吗?

更新

我不能使用单例模式,因为MyService.Context会根据发出请求的用户(通过HttpContext)进行更改.

I can't use a singleton pattern since MyService.Context changes depending on the user making a request (via HttpContext).

在上述lambda参数中的伪代码中,参数c表示SM上下文,因此我可以为每个请求返回自定义结果.我知道SM的Intercept(),但是在构造对象后 被触发了-不是代替.

In the pseudo-code above lambda parameter c represents a SM context, so that i can return a custom result for each request. I'm aware of SM's Intercept() but it's fired after the object is constructed - not instead.

推荐答案

如果可以使用属性,则可以添加OnCreation方法.创建后立即对实例执行提供的操作:

If you can work with a property there is the possibility to add a OnCreation method. The Action provided is executed against the instance just after creation:

ObjectFactory.Initialize(x =>
        {
            x.For<IMyService>()
             .Use<MyInstance>()
             .OnCreation(x => x.Context = MyService.Context;
        });

或者您可以使用延迟初始化,并为Use方法提供一个Func,只要需要新实例,该方法就会执行.这应该在正确的上下文中执行:

Or you can use lazy initialization and provide a Func to the Use method which is executed whenever a new instance is needed. This should execute in the right context:

ObjectFactory.Initialize(x =>
        {
            x.For<IMyService>()
             .Use<MyInstance>(() => new MyInstance(MyService.Context);
        });

我希望其中一种方法对您有用.

I hope one of this methods works for you.

这篇关于在StructureMap中注册默认实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆