我有来自相同接口的服务
public interface IService { }
public class ServiceA : IService { }
public class ServiceB : IService { }
public class ServiceC : IService { }
Run Code Online (Sandbox Code Playgroud)
通常,其他IOC容器Unity
允许您通过某些Key
区分它们来注册具体实现.
在Asp.Net Core中,我如何注册这些服务并在运行时根据某些键解决它?
我没有看到任何通常用于区分具体实现的Add
Service方法key
或name
参数.
public void ConfigureServices(IServiceCollection services)
{
// How do I register services here of the same interface
}
public MyController:Controller
{
public void DoSomeThing(string key)
{
// How do get service based on key
}
}
Run Code Online (Sandbox Code Playgroud)
工厂模式是唯一的选择吗?
Update1
我已经阅读了这里 …
突然之间,升级Nuget软件包时出现此错误.我遇到过的修复工作都没有.我正在使用Visual Studio 2013.
已经安装了"Newtonsoft.Json 6.0.3".
将"Newtonsoft.Json 6.0.3"添加到Tournaments.Notifications中.
成功将"Newtonsoft.Json 6.0.3"添加到Tournaments.Notifications中.
执行脚本文件'F:\ My Webs\BasketballTournaments\MainBranch\packages\Newtonsoft.Json.6.0.3\tools\install.ps1'.
无法初始化PowerShell主机.如果PowerShell执行策略设置设置为AllSigned,请打开程序包管理器控制台以首先初始化主机.
包管理器控制台
尝试在"FileSystem"提供程序上执行InitializeDefaultDrives操作失败.
如果我等待初始化在控制台中完成,我可以添加一些包.
powershell powershell-2.0 nuget nuget-package visual-studio-2013
(与此问题相关,EF4:为什么在启用延迟加载时必须启用代理创建?).
我是DI的新手,所以请耐心等待.我知道容器负责实例化我所有已注册的类型,但为了做到这一点,它需要引用我的解决方案中的所有DLL及其引用.
如果我没有使用DI容器,我就不必在我的MVC3应用程序中引用EntityFramework库,只需引用我的业务层,它将引用我的DAL/Repo层.
我知道在一天结束时所有的DLL都包含在bin文件夹中,但我的问题是必须通过VS中的"添加引用"显式引用它,以便能够发布包含所有必需文件的WAP.
我已经按照本教程进行了很好的工作,直到我修改了我DbContext
有一个额外的构造函数.我现在遇到了解决方案的问题,不知道如何解决这个问题.是否有一种简单的方法可以强制它抓住无参数构造函数,或者我接近这个错误?
DbContext
有两个构造函数:
public class DashboardDbContext : DbContext
{
public DashboardDbContext() : base("DefaultConnection") { }
public DashboardDbContext(DbConnection dbConnection, bool owns)
: base(dbConnection, owns) { }
}
Run Code Online (Sandbox Code Playgroud)
SiteController
构造函数:
private readonly IDashboardRepository _repo;
public SiteController(IDashboardRepository repo)
{
_repo = repo;
}
Run Code Online (Sandbox Code Playgroud)
库:
DashboardDbContext _context;
public DashboardRepository(DashboardDbContext context)
{
_context = context;
}
Run Code Online (Sandbox Code Playgroud)
UnityResolver
码:
public class UnityResolver : IDependencyResolver
{
private readonly IUnityContainer _container;
public UnityResolver(IUnityContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{ …
Run Code Online (Sandbox Code Playgroud) 我有以下通用扩展方法:
public static T GetById<T>(this IQueryable<T> collection, Guid id)
where T : IEntity
{
Expression<Func<T, bool>> predicate = e => e.Id == id;
T entity;
// Allow reporting more descriptive error messages.
try
{
entity = collection.SingleOrDefault(predicate);
}
catch (Exception ex)
{
throw new InvalidOperationException(string.Format(
"There was an error retrieving an {0} with id {1}. {2}",
typeof(T).Name, id, ex.Message), ex);
}
if (entity == null)
{
throw new KeyNotFoundException(string.Format(
"{0} with id {1} was not found.",
typeof(T).Name, id));
}
return …
Run Code Online (Sandbox Code Playgroud) 我使用泛型方法有很多Funcy乐趣(有趣).在大多数情况下,C#类型推断足够聪明,可以找出它必须在我的泛型方法上使用的泛型参数,但现在我有一个C#编译器不成功的设计,而我相信它可以成功找到正确的类型.
在这种情况下,有人能告诉我编译器是否有点愚蠢,还是有一个非常清楚的原因导致它无法推断我的泛型参数?
这是代码:
类和接口定义:
interface IQuery<TResult> { }
interface IQueryProcessor
{
TResult Process<TQuery, TResult>(TQuery query)
where TQuery : IQuery<TResult>;
}
class SomeQuery : IQuery<string>
{
}
Run Code Online (Sandbox Code Playgroud)
一些不编译的代码:
class Test
{
void Test(IQueryProcessor p)
{
var query = new SomeQuery();
// Does not compile :-(
p.Process(query);
// Must explicitly write all arguments
p.Process<SomeQuery, string>(query);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么是这样?我在这里错过了什么?
这是编译器错误消息(它不会给我们留下太多想象):
无法从用法中推断出方法IQueryProcessor.Process(TQuery)的类型参数.尝试显式指定类型参数.
我认为C#应该能够推断它的原因是由于以下原因:
IQuery<TResult>
.IQuery<TResult>
类型实现的版本才是IQuery<string>
TResult必须的string
.解
对我来说,最好的解决方案是更改IQueryProcessor
界面并在实现中使用动态类型:
public interface IQueryProcessor
{
TResult Process<TResult>(IQuery<TResult> …
Run Code Online (Sandbox Code Playgroud) 假设我有一个名为Items的表(ID int,Done int,Total int)
我可以通过两个查询来完成:
int total = m.Items.Sum(p=>p.Total)
int done = m.Items.Sum(p=>p.Done)
Run Code Online (Sandbox Code Playgroud)
但我想在一个查询中执行此操作,如下所示:
var x = from p in m.Items select new { Sum(p.Total), Sum(p.Done)};
Run Code Online (Sandbox Code Playgroud)
当然有一种方法可以从LINQ语法中调用聚合函数......?
如何从容器中拉出瞬态物体?我是否必须在容器中注册它们并注入需要类的构造函数?将所有内容注入构造函数中感觉不太好.也只是为了一个类,我不想创建一个TypedFactory
并将工厂注入需要的类.
我想到的另一个想法是根据需要"新"起来.但我也在我的Logger
所有类中注入一个组件(通过属性).因此,如果我新建它们,我将不得不手动实例化Logger
这些类.如何继续为我的所有课程使用容器?
记录器注入:我的大多数类都Logger
定义了属性,除非存在继承链(在这种情况下,只有基类具有此属性,并且所有派生类都使用该属性).当这些通过Windsor容器实例化时,它们会将我的实现ILogger
注入其中.
//Install QueueMonitor as Singleton
Container.Register(Component.For<QueueMonitor>().LifestyleSingleton());
//Install DataProcessor as Trnsient
Container.Register(Component.For<DataProcessor>().LifestyleTransient());
Container.Register(Component.For<Data>().LifestyleScoped());
public class QueueMonitor
{
private dataProcessor;
public ILogger Logger { get; set; }
public void OnDataReceived(Data data)
{
//pull the dataProcessor from factory
dataProcessor.ProcessData(data);
}
}
public class DataProcessor
{
public ILogger Logger { get; set; }
public Record[] ProcessData(Data data)
{
//Data can have multiple Records
//Loop through the data and create new set …
Run Code Online (Sandbox Code Playgroud) 我试图将此代码用于NET.reflector.使用Reflexil,我试图用这个替换代码,
if(Input.GetKeyDown(KeyCode.Keypad5)) {
int i = 0;
Character localPlayer = PlayerClient.GetLocalPlayer().controllable.GetComponent<Character>();
foreach (UnityEngine.Object obj2 in UnityEngine.Object.FindObjectsOfType(typeof(LootableObject)))
{
if (obj2 != null)
{
i++;
LootableObject loot = (LootableObject) obj2;
Debug.Log("Loot "+i+": "+loot.transform.position.ToString());
CCMotor ccmotor = localPlayer.ccmotor;
if(ccmotor != null && tpPos1 != Vector3.zero) {
ccmotor.Teleport(loot.transform.position);
Notice.Popup("?", "Teleported to "+loot.name, 1.5f);
}
break;
}
}
Run Code Online (Sandbox Code Playgroud)
}
但是当我尝试编译时它给了我一个错误:
Line: 1 Column: 1 Error Number: CS0116 Error Message: "A namespace does not directly contain members such as fields or methods"
Run Code Online (Sandbox Code Playgroud)
我认为这是Unity代码.我不是那么有经验的.任何人都能解决这个问题吗?或者告诉我该怎么做?谢谢.
基于这篇文章,我正在尝试IActionFilter
为ASP.NET Core 创建一个实现,它可以处理控制器上标记的属性和控制器的操作.虽然读取控制器的属性很容易,但我无法找到一种方法来读取action方法中定义的属性.
这是我现在的代码:
public sealed class ActionFilterDispatcher : IActionFilter
{
private readonly Func<Type, IEnumerable> container;
public ActionFilterDispatcher(Func<Type, IEnumerable> container)
{
this.container = container;
}
public void OnActionExecuting(ActionExecutingContext context)
{
var attributes = context.Controller.GetType().GetCustomAttributes(true);
attributes = attributes.Append(/* how to read attributes from action method? */);
foreach (var attribute in attributes)
{
Type filterType = typeof(IActionFilter<>).MakeGenericType(attribute.GetType());
IEnumerable filters = this.container.Invoke(filterType);
foreach (dynamic actionFilter in filters)
{
actionFilter.OnActionExecuting((dynamic)attribute, context);
}
}
}
public void OnActionExecuted(ActionExecutedContext context)
{
throw …
Run Code Online (Sandbox Code Playgroud) c# ×7
.net ×5
asp.net-core ×2
asp.net-mvc ×1
button ×1
c#-4.0 ×1
coreclr ×1
dbcontext ×1
keycode ×1
linq ×1
linq-to-sql ×1
nuget ×1
powershell ×1
reflexil ×1
sum ×1