在Autofac中,是否每次解析另一个特定类型时都可以自动实例化类型,并为该特定类型创建命名作用域?
例如
exports.handler = function (event, context, callback) {
const promises = [];
const records = event["Records"];
for (let record of records) {
const message = JSON.parse(record.body);
const promise = scrapper.parseEngine(message.commands, null, null, null);
promises.push(promise);
}
Promise.all(promises).then((data) => {
console.log('promise finished');
callback(null, data);
}).catch((err) => {
console.log('error', err);
callback(err);
});
我已经使用Owned,OnActivated和每次builder.Register<MyType>.As<IMyType>().InstancePerLifetimeScope();
builder.RegisterAsAutoInstantiateType<IMyType, MySubType>().As<IMySubType>();
class MySubType(IMyType myType)
{
...
}
解析IEnumerable<IMySubType>
进行了尝试,但是我想要为每个IMyType
创建一个新的生存期范围,并且自动解析并实例化为此IMyType
范围注册的所有类型。
答案 0 :(得分:0)
以下代码按您的要求运行。唯一的策略是您的类型将实例化两次。为了克服这个问题,我进行了两次注册。请看一眼,让我们知道。
//Lighweight registration
containerBuilder.RegisterType<TestItem>().As<ITestItem>();
//Actual regirstation
containerBuilder.Register((c, qe) =>
{
var subType = c.Resolve<IsubType>();
return new TestItem(subType);
}).As<ITestItem>().Keyed("TestKey", typeof(ITestItem));
containerBuilder.RegisterBuildCallback(builtContainer =>
{
//Filter for types
foreach (var registration in builtContainer.ComponentRegistry.Registrations)
{
registration.Activating += (sender, eventArgs) =>
{
var instanseLookup = eventArgs.Context as IInstanceLookup;
if (instanseLookup != null && !instanseLookup.ActivationScope.Tag.Equals("Manual"))
{
var scope = builtContainer.BeginLifetimeScope("Manual");
eventArgs.Instance = scope.ResolveKeyed<ITestItem>("TestKey");
}
};
}
});