问题
Not very familiar with Windsor Container, modifying code written by other person. We have code which initializes all objects in WindsorContainer which has PgDataAccess (own class) data type property
public PgDataAccess da { get; set; }
Code is the following:
_windsorContainer.Register(Component.For<PgDataAccess>().UsingFactoryMethod(() =>
{
var dataAccess = new PgDataAccess();
dataAccess.ConnectionString = connectionString;
return dataAccess;
}));
According to some errors seems we had same PgDataAccess class instance is used for all the objects in this container. How to modify this initialization to register separate PgDataAccess class instance in every container's object? Something with following meaning:
foreach(component in _windsorContainer.Components.<PgDataAccess>())
{
var dataAccess = new PgDataAccess();
dataAccess.ConnectionString = connectionString;
component.da = dataAccess;
}
回答1:
In your code lifestyle of PgDataAccess is singleton, since "Singleton is the default lifestyle, which will be used if you don't specify anyone explicitly"
So, your code is similar to
_windsorContainer.Register(Component.For<PgDataAccess>()
.LifestyleSingleton()
.UsingFactoryMethod(() =>
{
var dataAccess = new PgDataAccess();
dataAccess.ConnectionString = connectionString;
return dataAccess;
}));
If you want to have new instance of PgDataAccess for each component that depends on it, you should register it as transient.
_windsorContainer.Register(Component.For<PgDataAccess>()
.LifestyleTransient()
.UsingFactoryMethod(() =>
{
var dataAccess = new PgDataAccess();
dataAccess.ConnectionString = connectionString;
return dataAccess;
}));
You can read more information about lifestyles here.
来源:https://stackoverflow.com/questions/19324033/how-to-register-separate-instance-of-a-class-using-windsor-container