ASP.NET核心。配置DI以获取不同接口

时间:2017-04-28 13:14:04

标签: c# asp.net-core asp.net-core-mvc asp.net-core-webapi

我有中间件,可以做一些工作并创建对象。我需要将此对象注入控制器。 到目前为止,我通过向DI添加一些工厂来看到带有额外层的解决方案,这些工厂通过从context.Items['myobject_created_and_placed_here_in_middleware']中提取已创建的对象来创建这些对象。

我也在考虑另一种方式:

public interface IReader
{
    string Get();
}

public interface IWriter
{
    string Set(string value);
}

public class Object1 : IReader, IWriter
{
    public string s1 { get; set; }
    public string Get()
    {
        return this.s1;
    }

    public string Set(string value)
    {
        this.s1 = value;
        return s1;
    }
}

public class Middleware1
{
    RequestDelegate next;
    private readonly IReader _reader;


    public Middleware1(RequestDelegate next, IReader reader)
    {
        this.next = next;
        _reader = reader;
    }

    public async Task Invoke(HttpContext context)
    {
        var test1 = _reader.Get();
        await next.Invoke(context);
    }
}

public class Middleware2
{
    RequestDelegate next;
    private readonly IWriter _writer;


    public Middleware2(RequestDelegate next, IWriter writer)
    {
        this.next = next;
        _writer = writer;
    }

    public async Task Invoke(HttpContext context)
    {
        _writer.Set("13168AAE-C886-453E-B655-ECE5D14645D9");
        await next.Invoke(context);
    }
}

Startup.cs:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();

        app.UseMiddleware<Middleware2>();
        app.UseMiddleware<Middleware1>();

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }

到目前为止,它不起作用 这将返回不同的对象:

services.AddScoped<IReader,Object1>();
services.AddScoped<IWriter, Object1>();

这无法解析界面:

services.AddScoped<Object1>();

问题是:如何在DI中注册它并为每个请求获取不同接口的相同对象。

2 个答案:

答案 0 :(得分:2)

仅供参考:可以在DI注册之间共享单个对象,甚至可以在ScopedTransient注册之间共享。尽可能避免使用它。

public interface IGodObject { } //empty marker interface
public interface IWriter { }
public interface IReader { }
public class GodObject : IGodObject, IReader, IWriter { }

services.AddScoped<IGodObject>(p =>
{
    return new GodObject();
});

services.AddScoped<IReader>(p =>
{
    return p.GetService<IGodObject>() as IReader;
});

services.AddScoped<IWriter>(p =>
{
    return p.GetService<IGodObject>() as IWriter;
});

答案 1 :(得分:1)

就个人而言,我会坚持HttpContext中的IReader属性,因为它的唯一目的是存储请求范围的项目。

但是,如果您想在DI中使用对象实例,我建议您将IWriterSELECT 'alter index' as 'reindex_part1', '[' + dbindexes.[name] + ']' as 'Index', 'on' as 'reindex_part2', '[' + dbtables.[name] + ']' as 'Table', CASE WHEN indexstats.avg_fragmentation_in_percent > 30 THEN 'rebuild with (FILLFACTOR = 80)' ELSE 'reorganize' END as 'reindex_part3', indexstats.avg_fragmentation_in_percent, indexstats.page_count, indexstats.alloc_unit_type_desc, dbschemas.[name] as 'Schema' FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id] INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id] INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[object_id] AND indexstats.index_id = dbindexes.index_id WHERE indexstats.database_id = DB_ID() AND indexstats.avg_fragmentation_in_percent > 5 ORDER BY indexstats.avg_fragmentation_in_percent desc 合并到一个接口中,并将其添加到DI容器中。