使用 Unity,我想执行一个方法来返回一个实例,每次解析类型时都应该将其注入到构造函数中。
即在下面的示例中,InitializeTest() 仅执行一次,即在定义 injectionContructor 时。理想情况下,它应该执行两次,每次 ITestClass 被解析一次。
public interface ITestClass
{
public string GetMyNumber();
}
public class TestClass : ITestClass
{
private int _myNumber;
public TestClass(int myNumber)
{
_myNumber = myNumber;
}
public string GetMyNumber()
{
return String.Format("My number is: {0}", _myNumber);
}
}
public class Controller
{
UnityContainer _container;
public Controller()
{
InitializeContainer();
}
public void InitializeContainer()
{
if(_container == null)
_container = new UnityContainer();
container.RegisterType<ITestClass>(new TransientLifetimeManager(), new InjectionConstructor(InitializeTest()));
}
public int InitializeTest()
{
return new Random().Next(100);
}
public void ExecuteController()
{
ITestClass class1 = _container.Resolve<ITestClass>();
ITestClass class2 = _container.Resolve<ITestClass>();
// both statements below print the same number
Console.WriteLine(class1.GetMyNumber());
Console.WriteLine(class2.GetMyNumber());
}
}