对于依赖注入解析器技术主题,我是一种新知识。我可以知道如何通过配置文件部分来解决依赖性。下面是我的类和接口以及配置文件。
我确定缺少某些代码/设置。您能帮我吗?
public interface IUserAuthentication
{
string Authenticate(string username, string password);
string GetUserRole(string username);
}
public class CloudAppAuthetication : IUserAuthentication
{
public string Authenticate(string username, string password)
{
//Jwt token based authentication logic should be there
return "This Authenticate method executed from cloud class";
}
public string GetUserRole(string username)
{
//New logic to user management api call
return "This GetUserRole method executed from cloud class";
}
}
public class StandaloneAppAuthetication : IUserAuthentication
{
public string Authenticate(string username, string password)
{
//current logic should be here
return "This Authenticate method executed from standalone class";
}
public string GetUserRole(string username)
{
//current logic should be here
return "This GetUserRole method executed from standalone class";
}
}
控制台方法的控制台应用程序调用:
class Program
{
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
container.LoadConfiguration("TestContainer");
IUserAuthentication _userAuthentication = null;
string validatedUser = _userAuthentication.Authenticate(
"testuser@user.com", "testpassword");
string validatedUserRole =
_userAuthentication.GetUserRole("testuser@user.com");
}
}
我的控制台应用程序的App.config文件是:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="unity"
type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
Microsoft.Practices.Unity.Configuration" />
</configSections>
<unity xmlns = "http://schemas.microsoft.com/practices/2010/unity" >
< container name="TestContainer">
<register
type="UnityConfiguration_Testing.IUserAuthentication,UnityConfiguration_Testing"
mapTo="UnityConfiguration_Testing.StandaloneAppAuthetication,UnityConfiguration_Testing"
/>
</container>
</unity>
<startup>
<supportedRuntime version = "v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
我正在将对象引用未设置为对象错误的实例。期望StandaloneAppAuthetication
类方法将按照我的配置执行。
答案 0 :(得分:0)
按照@qujck的建议,我进行了如下代码更改,效果很好。谢谢 qujck 。
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UnityConfiguration_Testing
{
class Program
{
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
container.LoadConfiguration("TestContainer");
var _userAuthentication = container.Resolve<IUserAuthentication>();
string validatedUser = _userAuthentication.Authenticate("testuser@user.com", "testpassword");
string validatedUserRole = _userAuthentication.GetUserRole("testuser@user.com");
}
}
}