Does autofac provide me with a way to get all "active" instances of a component? So that the following works:
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;
}
}开发者_C百科
Not out of the box I'm afraid - you'll need to come up with another scheme for this scenario. You might be able to use the OnActivated()
and OnRelease()
events to keep your own registry of active views:
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))
});
精彩评论