简体   繁体   English

注入合适的class C#

[英]Inject appropriate class C#

I need some advice on how to better structure my classes.我需要一些关于如何更好地组织我的课程的建议。

I have generic interface and class:我有通用接口和 class:

public interface IReader
{
        IEnumerable<Change> ReadChanges(string log, int count, string from);
}
public class Reader : IReader
    {
        private readonly MongoDb _db;

        public StageChangesReader(MongoDb db)
        {
            _db = db;
        }

        public IEnumerable<Change> ReadChanges(string log, int count, string from)
        {
             //....
        }
    }

Then I made three other classes that use this reader (they implement the same method and the only difference is log that I pas) something like this:然后我制作了其他三个使用这个阅读器的类(它们实现了相同的方法,唯一的区别是我通过的日志)是这样的:

 public class SpecificReader
    {
        private readonly IReader _reader;

        public SpecificReader(IReader reader)
        {
            _reader = reader;
        }

        public IEnumerable<Change> ReadChanges(int count, string from)
        {
            return _changesReader.ReadChanges("specific log", count, from);
        }
    }

finally in the third class I want to inject these and based on the type use specific logging in the function:最后在第三个 class 我想注入这些,并根据 function 中使用特定日志记录的类型:

var changes = _type == MyType.SpecificReader
                ? _specificReader.ReadSpecific(_count, from)
                : _somethingElse.ReadSomethingElse(_count, from);

I would like to make this more generic that instead of having if I could pass this one generic method.我想让这个更通用,而不是if我可以通过这个通用方法。

so it would be like:所以它会像:

var changes = _Reader.ReadChanges(_count, from)

Is that possible?那可能吗?

Considering adding a method in your interface and either overwriting it in your derived concrete classes, so you can call IConcreteClass.LogMethod() on all of them, making them responsible for the way they log.考虑在您的接口中添加一个方法并在派生的具体类中覆盖它,这样您就可以在所有这些类上调用 IConcreteClass.LogMethod() ,使它们对它们的日志方式负责。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM