Ninject会在当前创建所有实例吗?

时间:2018-02-16 08:41:06

标签: c# ninject

有没有办法检索已经实例化的IMyInterface列表尚未处理? 例如:

  @Override
protected void onViewHolderBind(List<SampleBean> list, RecyclerView.ViewHolder holder, int position) {
    final ItemVH itemVH = (ItemVH) holder;
    itemholder= itemVH;
    itemVH.tvTitle.setText(list.get(position).title);


     Thread t= new Thread(){
        @Override
        public void run() {
            super.run();
            imgwidth= itemVH.ımageView.getWidth();
            imgheight= itemVH.ımageView.getHeight();

            globalImg= itemVH.ımageView;
            itemVH.ımageView.getGlobalVisibleRect(rect);

        }
    };
    t.start();

    if(listwithBitmap.get(position).getCanvasBitmap() == null )
     new BackgroundTask().execute(position);

     else
     {
        itemholder.ımageView.setImageBitmap(listwithBitmap.get(position).getCanvasBitmap());
     }

}

1 个答案:

答案 0 :(得分:1)

虽然我不知道采用这种方法,但您可以使用ActivationActions轻松实现此目的。这允许您指定在为特定绑定创建对象时要执行的函数。然后你可以有一个ObjectTracker<T>类,使用弱引用来跟踪特定类的实例化:

public static class BindingExtension
{
    public static IBindingToSyntax<TInterface> TrackObjects<TInterface>(this IBindingToSyntax<TInterface> self)
        where TInterface : class
    {

        self.Kernel.Bind<ObjectTracker<TInterface>>().ToSelf().InSingletonScope();
        self.BindingConfiguration.ActivationActions.Add((c, o) =>
        {
            c.Kernel.Get<ObjectTracker<TInterface>>().Add((TInterface)o);
        });

        return self;
    }
}
// Usage
public class MyModule : NinjectModule
{
    public override void Load()
    {
        Bind<IMyInterface>()
            .TrackObjects()
            .To<MyImplementation>();//creates new instance on every Get<> call
    }
}

var a = kernel.Get<IMyInterface>();
var b = kernel.Get<IMyInterface>();
var c = kernel.Get<IMyInterface>();

var abcList = kernel.Get<ObjectTracker<IMyInterface>>().AllInstances.ToList();

// Helper class
public class ObjectTracker<T>
    where T: class
{
    private List<WeakReference<T>> instances = new List<WeakReference<T>>();
    public void Add(T item)
    {
        this.Prune(); // You could optimize how often you prune the list, with a counter for example.
        instances.Add(new WeakReference<T>(item));
    }
    public void Prune()
    {
        this.instances.RemoveAll(x => !x.TryGetTarget(out var _));
    }
    public IEnumerable<T> AllInstances => instances
        .Select(x =>
        {
            x.TryGetTarget(out var target);
            return target;
        })
        .Where(x => x != null);
}