Ninject 具有 Azure 辅助角色

Ninject with Azure Worker Role

我想在我的 WorkerRole 应用程序中使用 ninject 依赖注入器。 但是我发现了一些问题。在 运行 我的 worker 角色之后他立即崩溃了,我不知道为什么会这样。

我的WorkerRole.cs代码:

public class WorkerRole : NinjectRoleEntryPoint
    {
        private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
        private readonly ManualResetEvent _runCompleteEvent = new ManualResetEvent(false);

        private IKernel _kernel;
        public ITestA TestA { get; }
        protected WorkerRole(ITestA testA)
        {
            TestA = testA;
        }

        public override void Run()
        {
            Trace.TraceInformation("WorkerRole1 is running");

            try
            {
                RunAsync(_cancellationTokenSource.Token).Wait();
            }
            finally
            {
                _runCompleteEvent.Set();
            }
        }

        protected override IKernel CreateKernel()
        {
            _kernel = new StandardKernel();
            _kernel.Bind<ITestA>().To<TestA>();

            return _kernel;
        }

        private async Task RunAsync(CancellationToken cancellationToken)
        {
            // TODO: Replace the following with your own logic.
            while (!cancellationToken.IsCancellationRequested)
            {
                TestA.Hello();

                Trace.TraceInformation("Working");
                await Task.Delay(1000);
            }
        }
    }

然后我创建了一个简单的界面并为它 class,像这样:

public interface ITestA
    {
        void Hello();
    }

    public class TestA: ITestA
    {
        public void Hello()
        {
            Console.WriteLine("Ninject with Worker Role!");
        }
    }

这一切,我不知道为什么我的应用程序崩溃了,请帮我解决这个问题。 非常感谢。

您的问题很可能是因为您将 NinjectRoleEntryPoint 和 WorkerRole 保留在同一个 Worker Role 项目中。您应该只在您的 Worker Role 项目中保留 one RoleEntryPoint 实现,并且您的 NinjectRoleEntryPoint 应该移动到单独的 class 库项目。

简而言之 - 根据设计,您不能在一个 Worker Role 中拥有多个继承 RoleEntryPoint 的 classes。