如何从容器中拉出瞬态物体?我是否必须在容器中注册它们并注入需要类的构造函数?将所有内容注入构造函数中感觉不太好.也只是为了一个类,我不想创建一个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) 对不起,该帖子的标题很棒.我有点好奇知道以下问题是否有任何解决方案.情况是我有一个函数调用SaveSecurity();,我需要在每个函数后调用它.如下所示:
public void AddUser(string ID, string Name, string Password)
{
///some codes
SaveSecurity();
}
public void DeleteUser(User ObjUser)
{
///some codes
SaveSecurity();
}
public void AddPermission(string ID, string Name, AccessType Access)
{
///some codes
SaveSecurity();
}
public void DeletePermission(Permission ObjPermission)
{
///some codes
SaveSecurity();
}
public void AddRole(string ID, string Name)
{
Roles.AddRole(ID, Name);
SaveSecurity();
}
public void SaveSecurity()
{
///Saves the data
}
Run Code Online (Sandbox Code Playgroud)
还有很多.所以现在如果我们看一下所有函数的相似性,最后它会SaveSecurity()在函数结束后调用它.我的问题是:
有没有办法在每个函数之后调用此函数,而不是一次又一次地写同一行?
我的类图看起来像这样
我试图在我的应用程序中"注入"自定义跟踪方法.
我希望尽可能优雅,不需要修改现有的大部分代码,并且可以轻松启用/禁用它.
我能想到的一个解决方案是创建一个自定义Attribute,我将它附加到我想要跟踪的方法.
基本理念:
public class MethodSnifferAttribute : Attribute
{
private Stopwatch sw = null;
public void BeforeExecution()
{
sw = new Stopwatch();
sw.Start();
}
public void ExecutionEnd()
{
sw.Stop();
LoggerManager.Logger.Log("Execution time: " + sw.ElapsedMilliseconds);
}
}
public class MyClass
{
[MethodSniffer]
public void Function()
{
// do a long task
}
}
Run Code Online (Sandbox Code Playgroud)
是否有任何现有.NET属性为调用/结束方法提供回调?
目前我正在编写一个可以估算Azure应用程序成本的程序.为此,我有想法拦截将(间接)调用(Azure)服务器的所有方法.并且对于每种方法决定它所属的成本的哪个方面(例如(存储事务,服务总线事务,令牌请求等))
其中一个难点是我还想在模拟类/方法时拦截方法调用,因此该程序也可以在Azure应用程序的开发过程中用于(单元)测试.
所以我想知道是否有办法'订阅'类的方法.当调用此方法时,将触发事件.或者还有其他(更好的)解决方案来拦截存储事务,服务总线事务,令牌请求等,也用于发送例如存储事务但被模拟的类?
提前致谢
编辑1: 有没有人知道是否有一些(帮助者)类/库或引用包含/知道影响Azure应用程序成本的所有类/方法?
编辑2 这是实现上述问题的好方法吗?还是有其他选择吗?