通过BLL从DAL获取对象到通过泛型进行演示

时间:2013-11-10 08:23:42

标签: c# generics interface

我有一堆BLL对象,它们是在模型第一种情况下直接映射数据库中的实体。我通过BLL将DAL对象从DAL通过这样的接口(来自BLL层)接收到表示层:

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


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

在表示层中,我只是通过这个调用得到了对象:

ILanguage language = BLL.Repository.GetNewLanguage();

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

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

/芬兰。

2 个答案:

答案 0 :(得分:0)

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

Here

答案 1 :(得分:0)

嗯,已经有一段时间了,对不起!

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

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与存储库类分离的想法,在我想出这个问题的新线程中!

干杯芬兰人。