Autofac仅为实例化项目解析IEnumerable <tcomponent> </tcomponent>

时间:2010-11-16 21:04:21

标签: c# .net autofac

autofac是否为我提供了获取组件的所有“活动”实例的方法? 以下是有效的:

public class ViewManager {

    public ViewManager(Func<IEnumerable<MyView>> viewProvider, Func<string, MyView> viewFactory) {
        ViewProvider = viewProvider;
        ViewFactory = viewFactory;
    }

    public Func<IEnumerable<MyView>> ViewProvider { get; private set; }
    public Func<string, MyView> ViewFactory { get; private set; }

    public MyView GetView(string viewId) {
        var existing = from view in ViewProvider() //this would get me all the active views (not the available implementations)
                       where !view.IsDisposed
                             && view.Id == viewId
                       select view;
        return existing.FirstOrDefault() ?? ViewFactory(viewId);
    }
}

public class MyView: IDisposable {
    public MyView(string id) {
        Id = id;
    }
    public string Id { get; private set; }
    public bool IsDisposed { get; private set; }
    public void Dispose() {
        IsDisposed = true;
    }
}

1 个答案:

答案 0 :(得分:1)

我不敢开箱即用 - 您需要为此方案提出另一种方案。您可以使用OnActivated()OnRelease()事件来保留自己的活动视图注册表:

builder.RegisterType<ViewRegistry>()
  .As<IViewRegistry>()
  .SingleInstance();

builder.RegisterType<MyView>()
  .OnActivated(e =>
     e.Context.Resolve<IViewRegistry>().Add(e.Instance))
  .OnRelease(e => {
     e.Instance.Dispose();
     e.Context.Resolve<IViewRegistry>().Remove(e.Instance))
  });