关于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是两个全新的实例。应该怎么侬?
...全文
869 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)

62,046

社区成员

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

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

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

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