小编com*_*e73的帖子

ASP.NET core:需要显式访问 ServiceCollection?

我了解如何注册 ASP.NET core 的依赖项以及构造函数注入如何为我的控制器工作(我已经可以工作了)。是否所有内容都必须通过构造函数传递,然后显式传递到由这些构造对象创建的对象,或者实例化的对象(例如我的控制器)以及它们创建的对象如何使用服务集合来访问或实例化其他对象物体?

2020 年 6 月 19 日更新:

假设我的 Startup 调用了这个(这只是示例代码,看看我是否能得到这个问题,从而使我的帐户被取消):

    public static IServiceCollection AddRepository(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        var serviceProvider = services.BuildServiceProvider(); //TODO: dispose
        ContentstackClient stack = serviceProvider.GetService<ContentstackClient>();
        Trace.Assert(stack != null, "configure ContentstackClient service before IRepository service");
        IConfigureSerialization configurator = serviceProvider.GetService<IConfigureSerialization>();
        Trace.Assert(configurator != null, "configure IConfigureSerialization before ContentstackRepository");
        configurator.ConfigureSerialization(stack.SerializerSettings);
        //TODO: Apply ContentstackRepositoryConfiguration (UseSync, etc.) from appsettings.json
        ContentstackRepositoryConfiguration repoConfig = ContentstackRepositoryConfiguration.Get(
            ContentstackRepositoryConfiguration.StartType.FastestStartSync, stack);
            services.AddSingleton<IRepository>(new ContentstackRepository(repoConfig));//, serviceProvider.GetService<ILogger>()));
//TODO: happens automatically?            serviceProvider.Dispose();
            return services;
        }
Run Code Online (Sandbox Code Playgroud)

我的控制器中有这个:

    public EntryController( …
Run Code Online (Sandbox Code Playgroud)

.net c# .net-core

5
推荐指数
1
解决办法
1万
查看次数

C# 在运行时确定泛型类型参数

如果存在命名类,我想将该类作为类型参数传递给泛型方法。否则我想传递不同的类型。我不知道如何将类型参数传递给泛型方法。

// Does this type exist?
Type objType = Type.GetType(typeof(ModelFactory).Name + "." + content_type + "Model");

// if not, use this type instead
if (objType == null)
{
    objType = typeof(GenericModel);
}

// what to pass as the generic type argument?
var other = query.Find<objType>().ContinueWith((t) =>
Run Code Online (Sandbox Code Playgroud)

是否可以?我在最后一行中传递给 Find 而不是 objType 的是什么?

感谢和问候,

-约翰

c#

0
推荐指数
1
解决办法
117
查看次数

标签 统计

c# ×2

.net ×1

.net-core ×1