Nancy Autofac防止容器处理

时间:2018-07-21 18:46:04

标签: c# .net autofac nancy

是否有可能阻止Nancy为新请求重新排列容器?我创建了这个简单的代码来展示我的问题。 ConsoleWriter的构造函数每次都被调用,并且不希望发生这种情况。当然,我可以使ConsoleWriter成为一个单例,但是我的现实生活中的问题更加复杂,使数十个类的单例成为一个问题。因此,是否有可能迫使Nancy承认对象ConsoleWriter已经存在并使用它而不是创建新对象?

NancyApp.cs:

public class Program
{
    static void Main(string[] args)
    {
        var bootstrapper = new Bootstrapper();
        bootstrapper.Start();
        Console.ReadKey();
    }
}

Bootstraper.cs:

class Bootstrapper : AutofacNancyBootstrapper
{
    private IContainer _container;

    public void Start()
    {
        var builder = new ContainerBuilder();

        builder.RegisterType<ConsoleWriter>()
               .SingleInstance();
               //.ExternallyOwned()
               //.PropertiesAutowired();

        builder
            .RegisterType<ClientAPI>()
            .SingleInstance()
            .AutoActivate();

        builder
            .RegisterType<RestAPI>();
            //.ExternallyOwned()
            //.PropertiesAutowired();

        _container = builder.Build();
    }
}

ConsoleWriter.cs:

public class ConsoleWriter : IConsoleWriter
{
    private int _random_number;
    public ConsoleWriter()
    {
        _random_number = new Random().Next(0, 1000);
    }

    public int Value()
    {
        Console.WriteLine(_random_number);
        return _random_number;
    }
}

RestApi.cs:

public class RestAPI :NancyModule
{
    public RestAPI(ConsoleWriter consoleWriter)
    {
        Post["/click_1"] = param =>
        {
            Console.WriteLine("clicked_on_1");

            int value = consoleWriter.Value();

            return value.ToString();
        };

        Post["/click_2"] = param =>
        {
            Console.WriteLine("clicked_on_2");

            return "CLICKED_ON_2";
        };

        Post["/click_3"] = param =>
        {
            Console.WriteLine("clicked_on_3");

            return "CLICKED_ON_3";
        };
    }
}

输出:

  

随机数是:75

     

随机数是:342

     

随机数是:995

编辑:出于误导性问题,我已经清除了代码。

0 个答案:

没有答案