我需要在静态类中获取或访问我的 IoC 容器。这是我的(简化的)场景:
我在 Startup 类中注册 ASP .net Web Api 的依赖项(而且我也为 MVC 或 WCF 执行此操作。我有一个 DependecyResolver 项目,但为了简单起见,请考虑以下代码)
// Web Api project - Startup.cs
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
var builder = new ContainerBuilder();
// ... Omited for clarity
builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
.AsClosedTypesOf(typeof(IHandle<>))
.AsImplementedInterfaces();
// ...
IContainer container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
// ...
}
然后,在一个单独的类库中,我有我的静态类(为了清楚起见再次简化):
public static class DomainEvents
{
private static IContainer Container { get; set; }
static DomainEvents()
{
//Container = I need get my Autofac container here
}
public static void Register<T>(Action<T> callback) where T : IDomainEvent { /* ... */ }
public static void ClearCallbacks() { /* ... */ }
public static void Raise<T>(T args) where T : IDomainEvent
{
foreach (var handler in Container.Resolve<IEnumerable<IHandle<T>>>())
{
handler.Handle(args);
}
// ...
}
}
知道我怎样才能得到这个吗?
我需要在静态类中获取或访问我的 IoC 容器。
知道我怎样才能得到这个吗?
是的,你不知道!严重地。带有静态的图案DomainEvents
class 源自 Udi Dahan,但连 Udi 也承认这是一个糟糕的设计。需要自己的依赖关系的静态类使用起来非常痛苦。它们使系统难以测试和维护。
相反,创建一个IDomainEvents
抽象并将该抽象的实现注入到需要发布事件的类中。这完全解决了你的问题。
您可以定义您的DomainEvents
类如下:
public interface IDomainEvents
{
void Raise<T>(T args) where T : IDomainEvent;
}
// NOTE: DomainEvents depends on Autofac and should therefore be placed INSIDE
// your Composition Root.
private class AutofacDomainEvents : IDomainEvents
{
private readonly IComponentContext context;
public AutofacDomainEvents(IComponentContext context) {
if (context == null) throw new ArgumentNullException("context");
this.context = context;
}
public void Raise<T>(T args) where T : IDomainEvent {
var handlers = this.context.Resolve<IEnumerable<IHandle<T>>>();
foreach (var handler in handlers) {
handler.Handle(args);
}
}
}
您可以按如下方式注册此类:
IContainer container = null;
var builder = new ContainerBuilder();
builder.RegisterType<AutofacDomainEvents>().As<IDomainEvent>()
.InstancePerLifetimeScope();
// Other registrations here
container = builder.Build();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)