问题描述
,我所有的控制器接收的依赖和Autofac自动解决嵌套依赖。大它的工作原理
I am using Autofac with ASP.NET MVC integration, all my controllers receive dependencies and Autofac resolves nested dependencies automatically. Great it works
但我怎么能解决控制器实例的范围以外的依赖?在一些地方,我深深的code我要问的解析器我的记录器。一方面,它似乎是错误的是传递记录仪作为一个依赖下降到每一个小的对象创建,并在其他似乎错取决于依赖解析器在我的code如此之深。
But how can I resolve a dependency outside the scope of controller instantiation? In some places deep in my code I need to ask the resolver for my Logger. On the one hand it seems wrong to be passing the Logger as a dependency down to every little object I create, and on the other it seems to wrong to depend on dependency resolver so deep in my code
例如,我这是从许多动作返回的类名为结果。这是一个一致的使用对象,我的应用程序code可以依靠从更深的层次回来。当更深层次code增加了一个UI错误到这个对象我想自动添加到记录器,需要解决。让每类取记录器的依赖只会碍事
For example, I have a class called Result which is returned from many actions. It's a consistent used object that my application code can rely on coming back from the deeper layers. When the deeper layered code adds a UI error to this object I want to automatically add it to the logger, which needs resolving. Having every class take a dependency on logger would just get in the way
任何帮助AP preciated感谢
Any help appreciated thanks
推荐答案
那么,如果在每个对象的依赖激怒你,但我不事有什么错与中央记录器解析依赖性您可以使用事件触发(发布/订阅的方式)。
如果你真的需要从每个班级日志,那么你可以cetrtainly登录接近您的应用程序非常核心的方面,你精神上的形式给出它作为其他公共库类型(如String)或者整形这是普遍存在的,安全的依靠。
但我建议你别的东西。恕我直言,你应该rething架构和不每节课登录。如果你的日志只(或大部分)有关编写错误(例外),那么不要用它polute您的域模型。让我们将其放置在服务层来代替。这种编排层可以正确评估每个逮住例外,只记录是什么neccesary。让我们泡那些异常在堆栈跟踪下可能。安迪和处理他们在去年非常的事。
Well you can use eventing (pub/sub approach) if dependency in every object irritates you but i dont thing there is anything wrong with dependency on central Logger resolver.If you really need to log from every class then you cetrtainly can approach logging as very core aspect of your application and you mentally aproach it as other common library types like String or Ints which are ubiquitous and safe to depend on.But i would suggest you something else. IMHO you should rething the architecture and dont log in every class. If your logging is only (or mostly) about writing the errors (exceptions) then dont polute your domain model with it. Lets place it in Service layer insteád. This kind of orchestrating layer can correctly evaluate each catched exception and log only what is neccesary. Let's bubble those exceptions to the lower possible palce in the stack trace and handle them as last very thing.
这篇关于全球访问autofac在ASP.NET MVC3依赖解析器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!