【问题标题】:Get object from DAL via BLL into presentation via generics通过 BLL 从 DAL 获取对象到通过泛型表示
【发布时间】:2013-11-10 08:23:42
【问题描述】:

我有一堆 BLL 对象,它们是在模型优先场景中直接从数据库映射的实体。我通过像这样的接口(从 BLL 层)通过 BLL 从 DAL 获取这些对象到表示层:

    public static ILanguage GetNewLanguage()
    {
        return new Language();
    }


    public static bool SaveLanguage(ILanguage language)
    {
        return DAL.Repositories.LanguageRepository.Save(language);
    }

在表示层中,我只需通过此调用即可获得对象:

ILanguage 语言 = BLL.Repository.GetNewLanguage();

现在我有一堆对象,我想让 BLL 方法通用,所以我不必为每个对象编写相同的代码。

但我不知道该怎么做。如有任何帮助,谢谢。

/芬恩。

【问题讨论】:

    标签: c# generics interface


    【解决方案1】:

    为每个实体类型创建一个存储库类可能会导致大量冗余代码。只需通过以下示例代码使用通用存储库模式即可。

    Here

    【讨论】:

    • 罗杰,克鲁德!感谢您的观点,当我解决了问题中的实际核心后,我会仔细研究它,即如何实例化一个正在实现某个接口的类,然后将其返回。也许我正在通往 DI 的道路上,但同时我进入了 AppDomain.CurrentDomain.GetAssemblies() 和 Activator.CreateInstance。我会尽快发布解决方案。对不起,迟到的评论。干杯...
    【解决方案2】:

    好久不见,抱歉!

    我成功地创建了一个泛型方法。而不是每个实体都这样:

    public static ILanguage GetNewLanguage()
        {
            return new Language();
        }
    

    我现在正在使用这种通用方法(但我认为它仍然是一种笨拙的方法):

    public static T CreateNew<T>(out string errmsg) where T : class
        {
            errmsg = string.Empty;
    
            // Loading the DAL assembly as you cannot allways be sure that it is loaded,
            // as it can be used from the GAC and thereby not accessible as a loaded assembly.
            AppDomain.CurrentDomain.Load("DAL");
    
            // From loaded assemblies get the DAL and get the specific class that implements 
            // the interface provided, <T>.
            // It is assumed for the time being, that only one BLL dataobject implements the interface.
            var type = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(s => s.GetTypes())
                .Where(p => typeof(T).IsAssignableFrom(p) && p.IsClass)
                .FirstOrDefault();
    
            try
            {
                // Create an instance of the class that implements the interface in question, unwrap it 
                // and send it back as the interface type.
                var s = Activator.CreateInstance("DAL", type.FullName);
                return (T)s.Unwrap();
            }
            catch (Exception ex)
            {
                errmsg = ex.ToString();
                return null;
            }
    
        }
    

    来自表示层的调用现在如下所示:

    string errmsg = string.Empty;
    ILanguage language = BLL.CreateNew<ILanguage>(out errmsg);
    

    我解决了明显的问题,但仍然没有以一种奇特的方式。我有一个使用 DI 将程序集彼此分离的想法,但我不确定如何执行此操作。评论非常受欢迎。如果我找到一个解决方案,我会在新线程中发布解决方案。

    此外,当我弄清楚这一点后,我将在一个新线程中发布一个解决方案,以解决 Crud 关于如何使用存储库类将 BLL 与 DAL 分离的想法!

    芬恩干杯。

    【讨论】:

    • 通用方式当然有其缺点,因为它至少比直接方式慢 20-30 倍。所以这取决于性能和你的个人风格要实现什么......
    猜你喜欢
    • 2017-08-05
    • 2013-02-06
    • 1970-01-01
    • 2015-03-24
    • 2011-04-26
    • 2012-02-28
    • 2014-01-13
    • 2012-07-08
    • 1970-01-01
    相关资源
    最近更新 更多