a question about Autofac.Extras.CommonServiceLocator

258 views
Skip to first unread message

zhangb...@gmail.com

unread,
Mar 30, 2014, 1:27:02 AM3/30/14
to aut...@googlegroups.com
WebForms Global.asax


protected void Application_Start(object sender, EventArgs e)
{
var builder = new ContainerBuilder();
builder.RegisterType<Database>().InstancePerLifetimeScope();

var container = builder.Build();
_containerProvider = new ContainerProvider(container);

// Set the service locator to an AutofacServiceLocator
var csl = new AutofacServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => csl);
}

Page Default.aspx

public Database db1 { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
this.Title = Thread.CurrentThread.ManagedThreadId.ToString();
var db2 = ServiceLocator.Current.GetInstance<Database>();
this.Label1.Text = string.Format("db1:{0} db2:{1}", db1.GetHashCode(), db2.GetHashCode());
}

Run 1: db1:8934887 db2:22508250
Run 2: db1:11828856 db2:22508250
Run 3: db1:55103905 db2:22508250

I used InstancePerLifetimeScope,why it's the same in ServiceLocator? how to fix it?

thinks!

Travis Illig

unread,
Mar 31, 2014, 11:21:55 AM3/31/14
to aut...@googlegroups.com, zhangb...@gmail.com
The common service locator is a global construct and doesn't know anything about request lifetime scopes. So when you grab it and resolve something from it manually, it's going to resolve out of the root container. That's why you get the same value every time - you've registered the type "Database" as instance per lifetime scope, but the root container IS a lifetime scope and that's where it's coming from. Effectively, you're using a singleton.

If you need something per-request in your web form, you should inject it using constructor parameters. If you are in a web form and, for whatever reason, you have absolutely no choice but to use service location, you need to get your IContainerProvider and access the RequestLifetime. You can read about these things on the wiki here: https://github.com/autofac/Autofac/wiki/Web-Forms-Integration
Reply all
Reply to author
Forward
0 new messages