【问题标题】:How to Expose Class Types from a Component within a DLL如何从 DLL 中的组件公开类类型
【发布时间】:2021-01-23 18:03:42
【问题描述】:

我正在使用一家名为 Devart 的公司的组件。这个组件产生一个非常类似于实体框架的数据模型,除了它是用于 SQLite 的。我的数据模型和数据上下文等与实体框架的工作方式非常相似。

我创建了一个 Windows .NetFramework DLL 类库,我将使用它来处理我的许多与数据库相关的活动。在这个 DLL 中,我有我的数据模型和数据上下文,其中当然包含我所有的表类类型等。

在我的 DLL 中,我可以编写以下代码:

   public dbSales.tbl_Customers GetCustomer_byCustomerID(int _customerID)
   {
          dbSales.tbl_Customers selectedCustomer = (from dbContext.tbl_Customers 
                                                    where i.CustID == _customerID 
                                                     Select i).FirstOrDefault();
   }

然后在我的其他程序中,我想引用 DLL 和该方法来检索数据。我不知道如何公开我的表的类型以便我可以执行以下操作:我的 DLL 包含一个名为 DataHelper 的类。

(为清楚起见,代码以扩展形式编写)

DataHandler.DataHelper.tbl_Customers selectedCustomer = new DataHandler.DataHelper.tbl_Customers();
selectedCustomer = DataHandler.DataHelper.GetCustomer_byCustomerID(45);

我不知道如何公开类型:tbl_Customers。这只是我的无知。我发现的唯一解决方法是使用 var 执行以下操作。我喜欢能够指定我的类型,但不喜欢使用 var。以下作品:

var selectedCustomer = DataHandler.DataHelper.GetCustomer_byCustomerID(45);

我尝试过公开不同的东西,例如模型或上下文等。但仍然好像我只是公开方法和属性。我对类型以及如何使用它们一无所知。老实说,我很想找到一本解释类型以及如何使用它们的好书。

如果有人能提供这方面的帮助,将不胜感激。

【问题讨论】:

    标签: c# windows dll types .net-framework-4.8


    【解决方案1】:

    简单的解决方案是您可以像这样将类型标记为公共:

    public class MyClass{
    }
    

    默认情况下,类型是内部的,因此它们只能在同一个项目中访问。

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers

    比公开您的数据库实体类型更好的解决方案是创建域对象的类库。它们将是包含属性但不包含业务逻辑的类型,并且它们的属性将与您希望从数据访问项目中的相应类型公开的属性相同。然后,您可以使用 automapper 之类的工具从数据访问层返回这些类型。这有助于封装您的数据访问层。

    https://github.com/AutoMapper/AutoMapper

    例如,如果您的数据访问层有这样的Customer 类型

    internal class Customer
    {
        public int CustomerID { get; set; }
        public string Name { get; set; }
    }
    

    您的域层可以有一个名为Customer 的公共类,具有相同的属性。然后你可以像这样实现你的存储库:

    using Domain = MyDomainProject;
    
    public interface ICustomerRepository
    {
        Task<Domain.Customer> GetCustomerByIDAsync(int customerID);
    }
    
    internal class CustomerRepository : ICustomerRepository
    {
        private readonly DbContext context;
        private readonly IMapper mapper;
    
        public CustomerRepository (DbContext context, IMapper mapper)
        {
            this.context = context;
            this.mapper = mapper;
        }
    
        public async Task<Domain.Customer> GetCustomerByIDAsync(int customerID)
        {
            var customer = await context.Customer.FirstAsync(c => c.CustomerID == customerID);
            return mapper.Map<Domain.Customer>(customer);
        }
    }
    

    【讨论】:

    • 好的,谢谢您,我将使用您在此处提供的信息。我没有意识到类型是这样工作的。我之前考虑过创建自定义类对象并重新映射,但后来认为这可能比所需的工作量更多。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 2016-08-03
    • 2022-01-05
    • 1970-01-01
    • 2011-01-26
    • 2018-07-18
    • 1970-01-01
    相关资源
    最近更新 更多