注册要从工厂创建

Register to be created from factory

我正在尝试使用 DryIOC 来解析范围 entity framework 上下文。虽然这个注册有效,但感觉很奇怪:

container.Register<MyDbContext>( Reuse.ScopedTo<IMarkerInterface>(), Made.Of(() => Arg.Of<IDbContextFactory<MyDbContext>>().CreateDbContext()) );

特别是,Arg.Of 似乎打算以不同的方式使用。 Made 部分有更好的写法吗?

我可以使用 AddDbContextFactory() 和 (Microsoft-DI-) ServiceCollection 轻松注册 MyDbContext 的工厂,所以我这样做了。然后我使用 DryIoc.Microsoft.DependencyInjection 扩展名从 ServiceCollection 创建我的应用程序的其余部分使用的 DryIOC 容器。

现在在 DryIOC 世界里,我想要一个作用域MyDbContext。因此,我使用 ScopedTo 注册了 MyDbContext,但我希望每个上下文实例都由先前注册的(在 ServiceCollection 世界中)工厂生成。因此,DryIOC 应该解析工厂,调用创建并将结果放入当前范围,每次注入 MyDbContext

编辑:我已经升级到

container.Register<MyDbContext>( Reuse.ScopedTo<IMarkerInterface>(), Made.Of(container.Resolve<IDbContextFactory<MyDbContext>>(), factory => factory.CreateDbContext()) );

还是有点臭,因为Resolve前期不用了,总的来说感觉好多了。

container.Register<MyDbContext>( Reuse.ScopedTo<IMarkerInterface>(), Made.Of(() => container.Resolve<IDbContextFactory<MyDbContext>>(), factory => factory.CreateDbContext()) );

我想会很完美,但行不通(至少使用这种语法)。

据我了解,您需要这样的东西:

container.RegisterDelegate<IDbContextFactory<MyDbContext>, MyDbContext>(
    factory => factory.CreateDbContext(),
    Reuse.ScopedTo<IMarkerInterface>());