关于Autofac生命周期设置的问题

beckfun 2015-07-05 04:26:33
 
var builder = new ContainerBuilder();
builder.RegisterType<MyClass>().InstancePerLifetimeScope();

IContainer container = builder.Build();
// 第一次HTTP请求
var myClass1 = container.Resolve<MyClass>();
//第二次HTTP请求
var myClass2 = container.Resolve<MyClass>();

现在是myClass1 不会被丢掉,而是共享给myClas2继续用,我想要的是,myClass1 和myClas2是两个全新的实例。应该怎么侬?
...全文
871 27 打赏 收藏 转发到动态 举报
写回复
用AI写文章
27 条回复
切换为时间正序
请发表友善的回复…
发表回复
newtee 2015-07-06
  • 打赏
  • 举报
回复
这样用
  var _containerProvider = new ContainerProvider(new ContainerBuilder().Build());
            var test = _containerProvider.RequestLifetime.Resolve<Test>();

            this.Label1.Text = MyService.GetMsg()+test.GetMsg();
newtee 2015-07-06
  • 打赏
  • 举报
回复
   public partial class _Default : Page
{
public Test MyService { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
this.Label1.Text = MyService.GetMsg();
}
}


newtee 2015-07-06
  • 打赏
  • 举报
回复
弄给你看下吧


 public class Global : HttpApplication, IContainerProviderAccessor
{
// Provider that holds the application container.
static IContainerProvider _containerProvider;


public IContainerProvider ContainerProvider
{
get { return _containerProvider; }
}
protected void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码
AuthConfig.RegisterOpenAuth();
// Build up your application container and register your dependencies.
var builder = new ContainerBuilder();
builder.RegisterType<Test>().InstancePerRequest();
// ... continue registering dependencies...
// Once you're done registering things, set the container
// provider up with your registrations.
_containerProvider = new ContainerProvider(builder.Build());
}


void Application_End(object sender, EventArgs e)
{
// 在应用程序关闭时运行的代码

}

void Application_Error(object sender, EventArgs e)
{
// 在出现未处理的错误时运行的代码

}
}


 public class Test
{
public string GetMsg()
{
return "auto per request test";
}
}

webconfig
<?xml version="1.0" encoding="utf-8"?>
<!--
有关如何配置 ASP.NET 应用程序的详细信息,请访问
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-AutofacWebForm-20150706121558;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-AutofacWebForm-20150706121558.mdf" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<profile defaultProvider="DefaultProfileProvider">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</roleManager>
<!--
If you are deploying to a cloud environment that has multiple web server instances,
you should change session state mode from "InProc" to "Custom". In addition,
change the connection string named "DefaultConnection" to connect to an instance
of SQL Server (including SQL Azure and SQL Compact) instead of to SQL Server Express.
-->
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
<!--<httpModules>
--><!--This section is used for IIS6--><!--
<add name="ContainerDisposal" type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web" />
<add name="PropertyInjection" type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web" />
<add name="AttributeInjection" type="Autofac.Integration.Web.Forms.AttributedInjectionModule, Autofac.Integration.Web" />
</httpModules>-->
</system.web>
<system.webServer>
<!-- This section is used for IIS7 -->
<modules runAllManagedModulesForAllRequests="true">
<add name="ContainerDisposal" type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web" preCondition="managedHandler" />
<add name="PropertyInjection" type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web" preCondition="managedHandler" />
<add name="AttributedInjection" type="Autofac.Integration.Web.Forms.AttributedInjectionModule, Autofac.Integration.Web" preCondition="managedHandler" />
</modules>
</system.webServer>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>

引用 24 楼 beckfun 的回复:
别沉了...
beckfun 2015-07-06
  • 打赏
  • 举报
回复
别沉了...
beckfun 2015-07-05
  • 打赏
  • 举报
回复
引用 21 楼 zhuankeshumo 的回复:
https://media.readthedocs.org/pdf/autofac/latest/autofac.pdf 73页-74页 还有其他的自己看看
Add Modules to Web.config 这个也试过了。貌似不行...但是不清楚是不是我设置的不正确。关于你说的方式,我找的资料都是关于MVC的,没有WebForm的。
moonwrite 2015-07-05
  • 打赏
  • 举报
回复
webform是不支持构造函数注入的 用属性注入
newtee 2015-07-05
  • 打赏
  • 举报
回复
https://media.readthedocs.org/pdf/autofac/latest/autofac.pdf 73页-74页 还有其他的自己看看
beckfun 2015-07-05
  • 打赏
  • 举报
回复
引用 17 楼 zhuankeshumo 的回复:
自己去github autofac下面有个Autofac.Web的分支(给webform用的)https://github.com/autofac/Autofac.Web 把代码下载下来 测试用例一看就明白
已经反编译看过了。就是报 No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself. 这个错误。我没看懂这个错误啥意思..
beckfun 2015-07-05
  • 打赏
  • 举报
回复
蛋疼...
引用 18 楼 starfd 的回复:
线程单例应该没哪个IOC框架支持
[ThreadStatic]
        private static Reptile reptile;
        public static Reptile Reptile
        {
            get
            {
                if (reptile == null)
                {
                    reptile = new Reptile();//这里替换成IOC,每次请求创建一个实例
                }
                return reptile;
            }
        }
对啊,所以很奇怪呢。找个资料(当然英语水平有限,机器翻译看着想哭),看着云里雾里,哎...
  • 打赏
  • 举报
回复
线程单例应该没哪个IOC框架支持
[ThreadStatic]
        private static Reptile reptile;
        public static Reptile Reptile
        {
            get
            {
                if (reptile == null)
                {
                    reptile = new Reptile();//这里替换成IOC,每次请求创建一个实例
                }
                return reptile;
            }
        }
newtee 2015-07-05
  • 打赏
  • 举报
回复
自己去github autofac下面有个Autofac.Web的分支(给webform用的)https://github.com/autofac/Autofac.Web
把代码下载下来 测试用例一看就明白
beckfun 2015-07-05
  • 打赏
  • 举报
回复
引用 14 楼 starfd 的回复:
你的意思就是一直只有一个对象?单例吗?单例是下面这样子
builder.RegisterType<MyClass>().SingleInstance();
嗯,单例,但不是全局单例模式,是线程单例。也就是每个http请求是同一个共享体,另外的请求又是另外的一个共享体
beckfun 2015-07-05
  • 打赏
  • 举报
回复
引用 13 楼 zhuankeshumo 的回复:
上面的框架属于领域驱动设计
我不是MVC呢。我是webform...
  • 打赏
  • 举报
回复
你的意思就是一直只有一个对象?单例吗?单例是下面这样子
builder.RegisterType<MyClass>().SingleInstance();
newtee 2015-07-05
  • 打赏
  • 举报
回复
上面的框架属于领域驱动设计
newtee 2015-07-05
  • 打赏
  • 举报
回复
自己下载
http://codeplex.com/nopcommerce 看下 很容易的 这个 要加个AutofacRequestLifetimeHttpModule
beckfun 2015-07-05
  • 打赏
  • 举报
回复
引用 10 楼 starfd 的回复:
var builder = new ContainerBuilder();
        builder.RegisterType<MyClass>();
       
        IContainer container = builder.Build();
    // 第一次HTTP请求
        var myClass1 = container.Resolve<MyClass>();
    //第二次HTTP请求
        var myClass2 = container.Resolve<MyClass>();
简单的说这样就是每次请求都是一个全新的对象了
好吧,我现在也发现我提的问题让你们误解出在哪里了。 重新定义下

var builder = new ContainerBuilder();
        builder.RegisterType<MyClass>();
       
        IContainer container = builder.Build();
    // 第一次HTTP请求
        var myClass01 = container.Resolve<MyClass>();
        var myClass02 = container.Resolve<MyClass>();
        //myClass01和myClass02是同一个(共享)

    //第二次HTTP请求
        var myClass11 = container.Resolve<MyClass>();
        var myClass12 = container.Resolve<MyClass>();
        //myClass01和myClass02是同一个(共享)

//但是myClass01 和myClass11 不是同一个(不共享)

  • 打赏
  • 举报
回复
var builder = new ContainerBuilder();
        builder.RegisterType<MyClass>();
       
        IContainer container = builder.Build();
    // 第一次HTTP请求
        var myClass1 = container.Resolve<MyClass>();
    //第二次HTTP请求
        var myClass2 = container.Resolve<MyClass>();
简单的说这样就是每次请求都是一个全新的对象了
beckfun 2015-07-05
  • 打赏
  • 举报
回复
引用 8 楼 starfd 的回复:
就那个文档里面有的啊,InstancePerDependency 在其他容器中也称作瞬态或者工厂,使用Per Dependency作用域,服务对于每次请求都会返回单独的实例。 在没有指定其他参数的情况下,这是默认是作用域。
还不是很懂,InstancePerLifetimeScope=InstancePerDependency?
  • 打赏
  • 举报
回复
就那个文档里面有的啊,InstancePerDependency 在其他容器中也称作瞬态或者工厂,使用Per Dependency作用域,服务对于每次请求都会返回单独的实例。 在没有指定其他参数的情况下,这是默认是作用域。
加载更多回复(7)
前言在互联网时代,分布式应用、系统变得越来越多,我们在使用 .Net 技术构建分布式系统的时候,需要使用到一些组件或者是助手库来帮助我们提高生产力以及应用程序解耦,但是纵观.Net圈,能够符合要求的这样的组件并不是 很多,并且没有一个通用的抽象组件能够将这些接口集成起来,今天就为大家介绍一款开源的组件库 Foundatio,他们同样出自于Exceptionless团队之手,下面就来看看吧。目录Foundatio 介绍Getting Started缓存队列锁消息工作任务文件存储度量日志示例程序源码总结Foundatio 介绍GitHub : https://github.com/exceptionless/FoundatioFoundatio 是一个插件式的,松耦合的一套构建分布式应用的程序库,出自于Exceptionless团队。Foundatio 同时支持 .NET Framework 4.6 和 .NET Core。通过 Foundatio 我可以获得哪些帮助呢?如果你是面对接口(抽象)构建的程序,你可以很容易的对接口实现进行切换。具有友好的依赖注入,还在使用 .Net Framework的朋友可以体验一下,它具有比Autofac,Unity等更简易的操作和更友好的接口。可以更加方便的使用缓存了,Foundatio帮助我们封装了很多缓存的客户端实现,比如RedisCache、InMemoryCache、ScopedCache等等。消息总线,你不必自己构建或者使用复杂且昂贵的NServiceBus了,很多时候我们仅仅需要的是一个可以在本地或者云上运行的简单的消息总线。存储,现在你可以很方便的通过一致的接口来使用分布式存储了,包括内存文件存储、文件夹文件存储,Azure文件存储,AWS S3文件存储。Foundatio 主要包含以下模块:缓存(Caching)队列(Queues)锁(Locks)消息(Messaging)工作任务(Jobs)文件存储(File Storage)度量(Metrics)日志(Logging)这些组件都以NuGet包的形式提供出来供我们很方便的使用,下面依次来看看每一个组件的用途和使用方法吧。Getting Started缓存缓存是一种空间换时间的技术,你可以通过缓存来快速的获取一些数据。Foundatio Cache 提供了一致的接口ICacheClient 来很容易的存储或者读取缓存数据,并且提供了4中不同的缓存客户端的实现。他们分别是:1、InMemoryCacheClient:内存缓存的实现,这种缓存的生命周期为当前进程, 有一个MaxItems属性,可以设置最多缓存多少条数据。2、HybridCacheClient:InMemoryCacheClient 具有相同的实现,但是此接口提供、IMessageBus 可以用来跨线程之间的同步。3、RedisCacheClient:一个 Redis 客户端的实现。4、RedisHybridCacheClient:一个RedisCacheClient 、InMemoryCacheClient 的混合实现,通过RedisMessageBus来保持内存缓存跨线程之间的同步。注意:如果本地缓存的项已经存在,在调用Redis进行序列化保存的时候可能会有性能问题。5、ScopedCacheClient:传入ICacheClient和scope,scope 可以设置一个字符串,来制定一个缓存键前缀,这样可以很方便的进行批量存储和删除。例子:using Foundatio.Caching; ICacheClient cache = new InMemoryCacheClient(); await cache.SetAsync("test", 1); var value = await cache.GetAsync("test");队列提供了一个先进,先出的消息管道,Foundatio 提供了一个IQueue接口,并且拥有 4 种不同的队列实现。1、InMemoryQueue:一个内存队列实现,队列的生命周期为当前进程。2、RedisQueue:一个 Redis 队列实现。3、AzureServiceBusQueue:一个基于Azure的服务消息队列实现。4、AzureStorageQueue:一个基于Azure的存储队列实现。例子:using Foundatio.Queues; IQueue queue = new InMemoryQueue();await queue.EnqueueAsync(new SimpleWorkItem {     Data = "Hello"});var

62,050

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧