我在 appSettings.json 文件中有一个带有多个参数的 asp.net 核心 Web 应用程序。
我不想IOptions<MyObject>在构造函数中提供服务。
我想在构造函数中使用 MyObject。所以我找到了以下文章:https : //weblog.west-wind.com/posts/2017/dec/12/easy-configuration-binding-in-aspnet-core-revisited,这很有趣。
但我想更进一步。我想创建一个扩展方法来生成注入。
这是我想做的事情:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Common.WebTools.Extensions
{
public static class IServiceCollectionExtensions
{
public static IServiceCollection AddSingletonConfigurationObject<T>(this IServiceCollection services,
IConfiguration configuration,
string appSettingsKey) where T:new()
{
var obj2 = new T();
configuration.Bind(appSettingsKey, obj);
services.AddSingleton(obj2); //compilation failed
return services;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的 ConfigureServices 方法中我可以调用
services.AddSingletonConfigurationObject<Common.Tools.Configuration.GoogleAnalyticsConfiguration>(Configuration, "GoogleAnalytics");
Run Code Online (Sandbox Code Playgroud)
但我在这一行有一个编译错误:
services.AddSingleton(obj2);
Run Code Online (Sandbox Code Playgroud)
有人知道我该如何纠正错误吗?
c# dependency-injection asp.net-core-mvc .net-core asp.net-core
我有以下模型对象
[DataContract]
public class Filter
{
[DataMember (Name ="start")]
public int Start { get; set; }
[DataMember (Name="rows")]
public int Rows { get; set; }
[DataMember(Name = "geoloc")]
public GeoLocationModel GeoLocation { get; set; }
}
[DataContract]
public class GeoLocationModel
{
[DataMember(Name = "lat")]
public double Latitude { get; set; }
[DataMember(Name = "lng")]
public double Longitude { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
以及以下动作
[HttpGet]
public async Task GetCities([FromQuery]Models.Filters.Filter filters)
{
//some code
}
Run Code Online (Sandbox Code Playgroud)
当我使用以下查询调用操作时(由 axios 生成的查询):
/api/cities/?start=0&rows=5&geoloc=%7B%22lat%22:44,%22lng%22:3%7D
Run Code Online (Sandbox Code Playgroud)
参数 Start 和 …
下面是获取字符串的 Md5 值的以下 C# 代码
using System;
using System.Security.Cryptography;
using System.Text;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var urlPart = "dd5fad78903da9d3ce4905f8e731d6c4ýundefinedý3780534ý5";
Console.WriteLine("value= " + urlPart);
var md5val = md5(urlPart, Encoding.Default);
Console.WriteLine("md5= " + md5val);
}
public static string md5(string value, System.Text.Encoding encoding)
{
var buffer = encoding.GetBytes(value);
//Console.WriteLine("buffer= " + BitConverter.ToString(buffer));
MD5 md5Hasher = MD5.Create();
byte[] data = md5Hasher.ComputeHash(buffer);
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2")); …Run Code Online (Sandbox Code Playgroud)