gpt4 book ai didi

c# - 国际奥委会 : Dependency Injection and overall instances between assemblies

转载 作者:行者123 更新时间:2023-11-30 21:06:08 25 4
gpt4 key购买 nike

我听说这应该是可能的,但我无法想象这应该如何工作。

我正在为我的项目使用依赖注入(inject) (autofac)。我和别人一起开发一个项目,调用他的类的方法(我用的是他的汇编)。

然后我得到一个对象的实例,其他人应该将其用于他的操作。我们希望避免在每个方法上传递此对象实例并使用 autofac。

他可以在不传递任何参数的情况下在他的程序集项目中解析这个实例吗?我认为我们至少必须通过 DI-Container...但我听说依赖注入(inject)的概念应该使您可以在整个“执行上下文”中解析对象并获得相同的对象。

这是一个使用 asp.net web api 的例子:

这是一个asp.net webapi项目的api Controller :

public class DocumentsController : ApiController
{
// GET /api/documents
public HttpResponseMessage Get()
{
// Here I call the method of the other developer,
// security/authorization should be handled in
// his method!
// In this context the WebAPI provides the
// IPrincipal of the current user in this
// variable => "HttpContext.Current.User" but we
// don't want to pass it on every method call
ClassFromOtherAssembly.GetDocuments();

HttpResponseMessage response =
Request.CreateResponse<IEnumerable<Document>>(
HttpStatusCode.OK, documents);

return response;
}
}

这是其他开发者的类。他应该交付文件并检查用户是否被授权:

public class ClassFromOtherAssembly
{
public List<Documents> GetDocuments()
{
//Security check
IPrincipal principal =
DI_Container.Resolve(IPrincipal);

if(principal.IsInRole("Admin"))
{
//return the list
}
else
{
//return empty list
}
}
}

最佳答案

不,不要传递容器本身,你最终会得到一个服务定位器模式,如果你快速搜索一下,你就会明白这个模式有一股腐烂的味道。

public class Foo
{
private IContainer container;
private IBar bar;

public Foo( IContainer container) //no-no
{
this.container = container;
this.bar = container.Resolve<IBar>();
}
}

而是使用适当的 DI,例如

public class Foo
{
private IBar bar;

public Foo(IBar bar)
{
this.bar = bar;
}
}

您的类型在哪个程序集中并不重要。这就是 IoC 和 DI 的全部要点 - 分离应用程序的各个部分并使您依赖于抽象,而不是具体的实现。


编辑
您误解了 DI 的服务定位器模式。 “我们希望使用依赖注入(inject)而不是传递参数”- 传递参数是一个 DI,相比之下,从静态容器解析类型是一个服务定位器。

public class DocumentsController : ApiController
{
public HttpResponseMessage Get()
{
ClassFromOtherAssembly.GetDocuments(); //this is Service locator
//really bad for testability and maintenance
...
}
}

DI 看起来像这样

public class DocumentsController : ApiController
{
private IDocumentProvider;

public DocumentsController(IDocumentProvider provider)
{
this.provider = provider;
}

public HttpResponseMessage Get()
{
provider.GetDocuments(); //this is DI
...
}
}

关于c# - 国际奥委会 : Dependency Injection and overall instances between assemblies,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11359372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com