在请求期间向现有对象注入依赖项

本文关键字:对象 注入 依赖 请求 | 更新日期: 2023-09-27 17:58:50

Ninject为我创建了依赖于类B的类A的实例(因此Ninject也创建了对象B)。Ninject被配置为返回类A的单个实例(InSingletoScope)和类B的许多实例(InTrancitScope)。类A具有允许获取/设置对象B的依赖项的属性。

每次我请求类A的同一实例时,是否可以用新创建的实例B检索类A的实例?

如果OnActivation方法在每次请求时都执行,而不仅仅是第一次执行,那么它就能完成任务。

或者这可能是我要做的一些反模式?

编辑:为了避免XY问题,我将尝试解释更多细节。解决方案太大,无法解释一切——长话短说:

需要执行操作,例如盘点。操作由三个演示者(P1、P2、P3)填充。演示者管理相应的视图(V1、V2、V3)。用户在视图中输入数据,演示者从视图中获取数据并保存到操作。所有演示者和视图都是singleton(InSingletonScope),以避免每次需要时都创建对象。视图被注入到适当的演示者中。每次操作启动时,都应该创建新的操作实例,并将其注入到所有已存在的演示者中。

在请求期间向现有对象注入依赖项

每当您向IOC请求演示者时,它都会返回具有相同操作工厂的相同演示者。如果将IsValid设置为false,操作工厂可以返回相同的对象或新对象。为解决问题而创建的示例代码:

操作:

public abstract class Operation
    {
        protected Logger logger;
        public Operation(Logger logger)
        {
            this.logger = logger;
        }
    }

public class StocktakingOperation : Operation
    {
        public string test = DateTime.Now.ToString();
        public StocktakingOperation(Logger logger)
            : base(logger)
        {
        }
    }

工厂:

class OperationFactory<T> where T : Operation
    {
        private Func<T> ObjectCreation;
        private T ValidObject;

        public OperationFactory(Func<T> ObjectCreation)
        {
            IsValid = false;
            this.ObjectCreation = ObjectCreation;
        }

        /// <summary>
        /// While is True then the same operation is returned.
        /// Set it to False to invalidate current operation so the next call to get operation will return new operation.
        /// </summary>
        public bool IsValid { get; set; }

        public T GetOperation()
        {
            if (IsValid == false)
            {
                ValidObject = ObjectCreation();
                IsValid = true;
            }
            return ValidObject;
        }
    }

class StocktakingOperationFactory : OperationFactory<StocktakingOperation>
    {
        public StocktakingOperationFactory(Func<StocktakingOperation> ObjectCreation)
            : base(ObjectCreation)
        {
        }
    }

演示者

class StocktakingPresenter : BaseOperationPresenter<StocktakingPresentersManager, OPERATION_TYPE>
    {
        public StocktakingPresenter(QuickForm QuickForm, StocktakingOperationFactory OperationFactory, VIEW_TYPE view, Workspace workspace, Logger logger)
            : base(QuickForm, OperationFactory, view, workspace, logger)
        {}

    }

与IOC:

kernel.Bind<StocktakingOperation>().ToSelf();
kernel.Bind<StocktakingOperationFactory>().ToMethod(c =>
            new StocktakingOperationFactory(() => { return kernel.Get<StocktakingOperation>(); })
            ).InSingletonScope();
kernel.Bind<StocktakingPresenter>().ToSelf().InSingletonScope();