使用ASP.NET MVC的每个会话生活方式的Castle项目

Car*_*any 6 c# asp.net-mvc session castle-windsor ioc-container

我是Castle Windsor IoC容器的新手.我想知道是否有一种使用IoC容器存储会话变量的方法.我在想这个问题:

我想要一个类来存储搜索选项:

public interface ISearchOptions{
    public string Filter{get;set;}
    public string SortOrder{get;set;}
}

public class SearchOptions{
    public string Filter{get;set;}
    public string SortOrder{get;set;}
}
Run Code Online (Sandbox Code Playgroud)

然后将其注入必须使用它的类中:

public class SearchController{
    private ISearchOptions _searchOptions;
    public SearchController(ISearchOptions searchOptions){
        _searchOptions=searchOptions;
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后在我的web.config中,我配置城堡我希望有类似的东西:

<castle>
    <components>
        <component id="searchOptions" service="Web.Models.ISearchOptions, Web" type="Web.Models.SearchOptions, Web" lifestyle="PerSession" />
    </components>
</castle>
Run Code Online (Sandbox Code Playgroud)

让IoC容器处理会话对象,而不必自己显式访问它.

我怎样才能做到这一点?

谢谢.

编辑:正在做一些研究.基本上,我想要的是一个会话Scoped组件.我来自Java和Spring Framework,我有会话范围的bean,我认为它对存储会话数据非常有用.

Car*_*ist 14

这可能就是你要找的东西.

public class PerSessionLifestyleManager : AbstractLifestyleManager
    {
    private readonly string PerSessionObjectID = "PerSessionLifestyleManager_" + Guid.NewGuid().ToString();

    public override object Resolve(CreationContext context)
    {
        if (HttpContext.Current.Session[PerSessionObjectID] == null)
        {
            // Create the actual object
            HttpContext.Current.Session[PerSessionObjectID] = base.Resolve(context);
        }

        return HttpContext.Current.Session[PerSessionObjectID];
    }

    public override void Dispose()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

然后添加

<component
        id="billingManager"  
        lifestyle="custom"  
        customLifestyleType="Namespace.PerSessionLifestyleManager, Namespace"  
        service="IInterface, Namespace"
        type="Type, Namespace">
</component>
Run Code Online (Sandbox Code Playgroud)