【问题标题】:Could not load type 'CustomerMapping.DataAcessLayer.SqlDataAccess' from assembly无法从程序集中加载类型“CustomerMapping.DataAcessLayer.SqlDataAccess”
【发布时间】:2016-09-27 01:23:18
【问题描述】:

无法加载类型“CustomerMapping.DataAcessLayer.SqlDataAccess” 从程序集'CustomerMapping,版本=1.0.0.0,文化=中性, PublicKeyToken=null'。

我无法弄清楚是什么导致了我这辈子的这个异常。

这是我的 CustomerMapping 代码

        protected void btnAdd_Click(object sender, EventArgs e)
    {

        try
        {
            int result = new Customer() { LegalEntity = ddlLegalEntity.Text.Trim(), OldSourceEnvironment = ddlOldSourceEnvironment.Text.Trim(), OldCompanyCode = ddlOldCompanyCode.Text.Trim(), OldAccountNumber = txtOldAccountNumber.Text.Trim(), NewAccountNumber = txtNewAccountNumber.Text.Trim(), BusinessName = txtBusinessName.Text.Trim(), BusinessUnit = txtBusinessUnit.Text.Trim(), DefaultDimensionString = txtDefaultDimensionString.Text.Trim()}.AddCustomer();

            if (result > 0)
            {
                lvCustomers.EditIndex = -1;
                lblCurrent.Text = "Added Successfully!";
                ddlLegalEntity.Text = string.Empty;
                ddlOldSourceEnvironment.Text = string.Empty;
                ddlOldCompanyCode.Text = string.Empty;
                txtOldAccountNumber.Text = string.Empty;
                txtNewAccountNumber.Text = string.Empty;
                txtBusinessName.Text = string.Empty;
                txtBusinessUnit.Text = string.Empty;
                txtDefaultDimensionString.Text = string.Empty;
            }
            else
            {
                lvCustomers.EditIndex = -1;
                lblCurrent.Text = "Sorry, Add failed.";
            }
        }
        catch (Exception ex)
        {
            lblCurrent.Text = ex.Message;
        }
    }

这是用于 DataAccessLayer 的`

namespace CustomerMapping
{
public abstract class DataAccessLayer
{
    private string connectionString = ConfigurationManager.ConnectionStrings ["AXMAPConnectionString"].ToString();

    public string ConnectionString
    {
        get
        {
            if (!string.IsNullOrEmpty(connectionString))
                return connectionString;
            else
                throw new ApplicationException("Web.config ConnectionString Error. Check the App Settings in web.config and verify the connectionstring is present.");
        }
    }
    public static DataAccessLayer GetDataAccessLayer()
    {
        try
        {
            Type type = Type.GetType(Utility.DataAccessType, true);

            // Throw an error if wrong base type
            if (type.BaseType != typeof(DataAccessLayer))
                throw new Exception("Data Access Layer does not inherit DataAccessLayer!");

            return (DataAccessLayer)Activator.CreateInstance(type);
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }

    public abstract int AddCustomer(Customer customer);
 }
}

这是用于 SqlDataAccess 的

namespace CustomerMapping
{
public class SqlDataAccess : DataAccessLayer

{
    private SqlConnection sqlCn = null;

    private SqlConnection OpenConnection()
    {
        try
        {
            if (ConnectionString == string.Empty)
                throw (new ArgumentOutOfRangeException("ConnectionString"));

            sqlCn = new SqlConnection(ConnectionString);
            sqlCn.Open();
            return sqlCn;

        }
        catch (Exception ex)
        {
            throw new ApplicationException("DB Connection failed.", ex);
        }
    }
    private void CloseConnection()
    {
        if (sqlCn != null)
            sqlCn.Close();
    }

    public override int AddCustomer(Customer customer)
    {
        try
        {
            SqlCommand sqlCmd = new SqlCommand("INSERT INTO [AXMAP].[Customers] ([LegalEntity], [OldSourceEnvironment], [OldCompanyCode], [OldAcctNum], [AccountNum], [Name], [BusinessUnit], [DefaultDimensionStr]) VALUES (@LegalEntity, @OldSourceEnvironment, @OldCompanyCode, @OldAcctNum, @AccountNum, @Name, @BusinessUnit, @DefaultDimensionStr)");
            sqlCmd.Parameters.AddRange(new SqlParameter[] { new SqlParameter("@LegalEntity", customer.LegalEntity), new SqlParameter("@OldSourceEnvironment", customer.OldSourceEnvironment),
            new SqlParameter("@OldCompanyCode", customer.OldCompanyCode), new SqlParameter("@OldAcctNum", customer.OldAccountNumber), new SqlParameter("@AccountNum", customer.NewAccountNumber),
            new SqlParameter("@Name", customer.BusinessName), new SqlParameter("@BusinessUnit", customer.BusinessUnit), new SqlParameter("DefaultDimensionStr", customer.DefaultDimensionString) });

            sqlCmd.Connection = OpenConnection();
            int result = (int)sqlCmd.ExecuteScalar();
            sqlCmd.Connection.Close();
            return result;
        }
        catch (SqlException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

}
}


    <configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-CustomerMapping-20160522115525.mdf;Initial Catalog=aspnet-CustomerMapping-20160522115525;Integrated Security=True"
      providerName="System.Data.SqlClient" />
    <add name="AXMAPConnectionString" connectionString="Data Source=DESKTOP-IV1JN1C\SQLEXPRESS;Initial Catalog=AXMAP;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="DataAccessType" value="CustomerMapping.DataAcessLayer.SqlDataAccess" />
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="ConnectionString"/>
  </appSettings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
  <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>

【问题讨论】:

  • 你的 web.config 是什么样的?
  • 编辑原帖添加

标签: c# asp.net web-config typeloadexception


【解决方案1】:

命名空间不正确。应该是CustomerMapping.SqlDataAccess

<add key="DataAccessType" value="CustomerMapping.SqlDataAccess,CustomerMapping" />

反射会像

(DataAccessLayer)Activator.CreateInstance(
    "CustomerMapping.SqlDataAccess,CustomerMapping");

仅供参考:看起来你正在做穷人的依赖注入。为什么不使用 Autofac、Ninject 或 Structure Map 等 IoC 容器使用正确的 DI。

【讨论】:

  • 反射是什么意思?这是我需要补充的吗?我正在努力学习 DI 以及如何正确地做到这一点。
  • 你在做什么是用反射创建一个实例?你可以阅读更多here。如果您想了解 DI(依赖注入),请阅读Dependency Injection in .NET by Mark Seemann
  • 你的回答和我的有什么不同? stackoverflow.com/a/37505157/109941
  • @JimG。查看 OP 的 SqlDataAccess 类。 SqlDataAccessDataAccessLayer 都在 CustomerMapping 命名空间中,因此访问 SqlDataAccess 的正确方法是通过 CustomerMapping.SqlDataAccess
猜你喜欢
  • 1970-01-01
  • 2012-05-05
  • 1970-01-01
  • 2011-09-07
  • 2010-11-30
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
  • 2021-05-30
相关资源
最近更新 更多